Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1cd8aa9e17 | ||
|
|
1a07826513 |
@@ -1,5 +1,5 @@
|
||||
<p align="center">
|
||||
<img alt="logo" width="150" src="resources/logo_round.png" >
|
||||
<img alt="logo" src="resources/logo_round.png" >
|
||||
</p>
|
||||
|
||||
# @LightningTipBot 🏅
|
||||
|
||||
@@ -7,11 +7,11 @@
|
||||
|
||||
help - Read the help.
|
||||
balance - Check balance.
|
||||
transactions - List transactions
|
||||
tip - Reply to a message to tip: /tip 50
|
||||
send - Send funds to a user: /send 100 @LightningTipBot
|
||||
invoice - Receive with Lightning: /invoice 1000
|
||||
pay - Pay with Lightning: /pay lnbc10n1ps...
|
||||
donate - Donate: /donate 1000
|
||||
faucet - Create a faucet: /faucet 2100 21
|
||||
tipjar - Create a tipjar: /tipjar 100 10
|
||||
advanced - Advanced help
|
||||
+1
-4
@@ -2,7 +2,6 @@ bot:
|
||||
http_proxy: ""
|
||||
lnurl_public_host_name: "mylnurl.com"
|
||||
lnurl_server: "https://mylnurl.com"
|
||||
lnurl_image: true
|
||||
telegram:
|
||||
message_dispose_duration: 10
|
||||
api_key: "1234"
|
||||
@@ -15,6 +14,4 @@ lnbits:
|
||||
database:
|
||||
db_path: "data/bot.db"
|
||||
buntdb_path: "data/bunt.db"
|
||||
transactions_path: "data/transactions.db"
|
||||
shop_buntdb_path: "data/shop.db"
|
||||
groupsdb_path: "data/groups.db"
|
||||
transactions_path: "data/transactions.db"
|
||||
@@ -1,11 +1,9 @@
|
||||
module github.com/LightningTipBot/LightningTipBot
|
||||
|
||||
go 1.17
|
||||
go 1.15
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v0.3.1
|
||||
github.com/PuerkitoBio/goquery v1.8.0
|
||||
github.com/btcsuite/btcd v0.20.1-beta.0.20200515232429-9f0179fd2c46
|
||||
github.com/eko/gocache v1.2.0
|
||||
github.com/fiatjaf/go-lnurl v1.8.4
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0
|
||||
@@ -13,7 +11,6 @@ require (
|
||||
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
|
||||
@@ -21,12 +18,10 @@ require (
|
||||
github.com/sirupsen/logrus v1.6.0
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||
github.com/tidwall/buntdb v1.2.7
|
||||
github.com/tidwall/gjson v1.12.1
|
||||
github.com/tidwall/sjson v1.2.4
|
||||
golang.org/x/net v0.0.0-20210916014120-12bc252f5db8
|
||||
golang.org/x/text v0.3.6
|
||||
github.com/tidwall/gjson v1.10.2
|
||||
golang.org/x/text v0.3.5
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0
|
||||
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220326213923-f323bb71ac8e
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211217193303-c005cce171ac
|
||||
gorm.io/driver/sqlite v1.1.4
|
||||
gorm.io/gorm v1.21.12
|
||||
)
|
||||
|
||||
@@ -9,8 +9,6 @@ github.com/NebulousLabs/fastrand v0.0.0-20181203155948-6fb6489aac4e/go.mod h1:Bd
|
||||
github.com/NebulousLabs/go-upnp v0.0.0-20180202185039-29b680b06c82/go.mod h1:GbuBk21JqF+driLX3XtJYNZjGa45YDoa9IqCTzNSfEc=
|
||||
github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE=
|
||||
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
|
||||
github.com/PuerkitoBio/goquery v1.8.0 h1:PJTF7AmFCFKk1N6V6jmKfrNH9tV5pNE6lZMkG0gta/U=
|
||||
github.com/PuerkitoBio/goquery v1.8.0/go.mod h1:ypIiRMtY7COPGk+I/YbZLbxsxn9g5ejnI2HSMtkjZvI=
|
||||
github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
|
||||
github.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
|
||||
github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo=
|
||||
@@ -30,8 +28,6 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF
|
||||
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
|
||||
github.com/allegro/bigcache/v2 v2.2.5 h1:mRc8r6GQjuJsmSKQNPsR5jQVXc8IJ1xsW5YXUYMLfqI=
|
||||
github.com/allegro/bigcache/v2 v2.2.5/go.mod h1:FppZsIO+IZk7gCuj5FiIDHGygD9xvWQcqg1uIPMb6tY=
|
||||
github.com/andybalholm/cascadia v1.3.1 h1:nhxRkql1kdYCc8Snf7D5/D3spOX+dBgjA6u8x004T2c=
|
||||
github.com/andybalholm/cascadia v1.3.1/go.mod h1:R4bJ1UQfqADjvDa4P6HZHLh/3OxWWEqc0Sk8XGwHqvA=
|
||||
github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ=
|
||||
github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ=
|
||||
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
|
||||
@@ -87,7 +83,6 @@ github.com/btcsuite/snappy-go v1.0.0 h1:ZxaA6lo2EpxGddsA8JwWOcxlzRybb444sgmeJQMJ
|
||||
github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc=
|
||||
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792 h1:R8vQdOQdZ9Y3SkEwmHoWBmX1DNXhXZqlTpq6s4tyJGc=
|
||||
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY=
|
||||
github.com/btcsuite/winsvc v1.0.0 h1:J9B4L7e3oqhXOcm+2IuNApwzQec85lE+QaikUcCs+dk=
|
||||
github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs=
|
||||
github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ=
|
||||
github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4=
|
||||
@@ -140,8 +135,6 @@ github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.m
|
||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||
github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk=
|
||||
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
|
||||
github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM=
|
||||
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
|
||||
github.com/fiatjaf/go-lnurl v1.4.0 h1:hVFEEJD2A9D6ojEcqLyD54CM2ZJ9Tzs2jNKw/GNq52A=
|
||||
github.com/fiatjaf/go-lnurl v1.4.0/go.mod h1:BqA8WXAOzntF7Z3EkVO7DfP4y5rhWUmJ/Bu9KBke+rs=
|
||||
github.com/fiatjaf/go-lnurl v1.8.3 h1:ONQUQsXIZKkzrzax2SMUr5W0PreluhO4tct1JM0V/MA=
|
||||
@@ -176,15 +169,10 @@ github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1
|
||||
github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc=
|
||||
github.com/go-openapi/strfmt v0.19.5/go.mod h1:eftuHTlB/dI8Uq8JJOyRlieZf+WkkxUuk0dgdHXr2Qk=
|
||||
github.com/go-openapi/swag v0.0.0-20160704191624-1d0bd113de87/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I=
|
||||
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
|
||||
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
|
||||
github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
|
||||
github.com/go-redis/redis/v8 v8.8.2 h1:O/NcHqobw7SEptA0yA6up6spZVFtwE06SXM8rgLtsP8=
|
||||
github.com/go-redis/redis/v8 v8.8.2/go.mod h1:F7resOH5Kdug49Otu24RjHWwgK7u9AmtqWMnCV1iP5Y=
|
||||
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
|
||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||
github.com/goccy/go-yaml v1.9.5/go.mod h1:U/jl18uSupI5rdI2jmuCswEA2htH9eXfferR3KfscvA=
|
||||
github.com/gogo/googleapis v1.1.0/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s=
|
||||
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
|
||||
github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
|
||||
@@ -271,7 +259,6 @@ github.com/jackpal/gateway v1.0.5/go.mod h1:lTpwd4ACLXmpyiCTRtfiNyVnUmqT9RivzCDQ
|
||||
github.com/jackpal/go-nat-pmp v0.0.0-20170405195558-28a68d0c24ad/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc=
|
||||
github.com/jedib0t/go-pretty v4.3.0+incompatible/go.mod h1:XemHduiw8R651AF9Pt4FwCTKeG3oo7hrHJAoznj9nag=
|
||||
github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||
github.com/jessevdk/go-flags v1.4.0 h1:4IU2WS7AumrZ/40jfhf4QVDMsQwqA7VEHozFRrGARJA=
|
||||
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||
github.com/jinzhu/configor v1.2.1 h1:OKk9dsR8i6HPOCZR8BcMtcEImAFjIhbJFZNyn5GCZko=
|
||||
github.com/jinzhu/configor v1.2.1/go.mod h1:nX89/MOmDba7ZX7GCyU/VIaQ2Ar2aizBl2d3JLF/rDc=
|
||||
@@ -317,7 +304,6 @@ github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORN
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
|
||||
github.com/lightninglabs/gozmq v0.0.0-20191113021534-d20a764486bf h1:HZKvJUHlcXI/f/O0Avg7t8sqkPo78HFzjmeYFl6DPnc=
|
||||
github.com/lightninglabs/gozmq v0.0.0-20191113021534-d20a764486bf/go.mod h1:vxmQPeIQxPf6Jf9rM8R+B4rKBqLA2AjttNxkFBL2Plk=
|
||||
github.com/lightninglabs/neutrino v0.11.0/go.mod h1:CuhF0iuzg9Sp2HO6ZgXgayviFTn1QHdSTJlMncK80wg=
|
||||
@@ -343,13 +329,8 @@ github.com/mailru/easyjson v0.0.0-20160728113105-d5b7844b561a/go.mod h1:C1wdFJiN
|
||||
github.com/makiuchi-d/gozxing v0.0.2 h1:TGSCQRXd9QL1ze1G1JE9sZBMEr6/HLx7m5ADlLUgq7E=
|
||||
github.com/makiuchi-d/gozxing v0.0.2/go.mod h1:Tt5nF+kNliU+5MDxqPpsFrtsWNdABQho/xdCZZVKCQc=
|
||||
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
|
||||
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
|
||||
github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
|
||||
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
|
||||
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
|
||||
github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||
github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
|
||||
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
|
||||
github.com/mattn/go-sqlite3 v1.14.5 h1:1IdxlwTNazvbKJQSxoJ5/9ECbEeaTTyeU7sEAZ5KKTQ=
|
||||
@@ -382,8 +363,6 @@ github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzE
|
||||
github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
|
||||
github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.1.2 h1:QHYxcUJnGHBaq7XbvgunmZ2Pn0focXFqTD61CkH146c=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.1.2/go.mod h1:d++QJC9ZVf7pa48qrsRWhMJ5pSHIPmS3OLqK1niyLxs=
|
||||
github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78=
|
||||
@@ -525,8 +504,6 @@ github.com/tidwall/gjson v1.6.1 h1:LRbvNuNuvAiISWg6gxLEFuCe72UKy5hDqhxW/8183ws=
|
||||
github.com/tidwall/gjson v1.6.1/go.mod h1:BaHyNc5bjzYkPqgLq7mdVzeiRtULKULXLgZFKsxEHI0=
|
||||
github.com/tidwall/gjson v1.10.2 h1:APbLGOM0rrEkd8WBw9C24nllro4ajFuJu0Sc9hRz8Bo=
|
||||
github.com/tidwall/gjson v1.10.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/gjson v1.12.1 h1:ikuZsLdhr8Ws0IdROXUS1Gi4v9Z4pGqpX/CvJkxvfpo=
|
||||
github.com/tidwall/gjson v1.12.1/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/grect v0.1.3 h1:z9YwQAMUxVSBde3b7Sl8Da37rffgNfZ6Fq6h9t6KdXE=
|
||||
github.com/tidwall/grect v0.1.3/go.mod h1:8GMjwh3gPZVpLBI/jDz9uslCe0dpxRpWDdtN0lWAS/E=
|
||||
github.com/tidwall/lotsa v1.0.2 h1:dNVBH5MErdaQ/xd9s769R31/n2dXavsQ0Yf4TMEHHw8=
|
||||
@@ -542,8 +519,6 @@ github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
|
||||
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/tidwall/rtred v0.1.2 h1:exmoQtOLvDoO8ud++6LwVsAMTu0KPzLTUrMln8u1yu8=
|
||||
github.com/tidwall/rtred v0.1.2/go.mod h1:hd69WNXQ5RP9vHd7dqekAz+RIdtfBogmglkZSRxCHFQ=
|
||||
github.com/tidwall/sjson v1.2.4 h1:cuiLzLnaMeBhRmEv00Lpk3tkYrcxpmbU81tAY4Dw0tc=
|
||||
github.com/tidwall/sjson v1.2.4/go.mod h1:098SZ494YoMWPmMO6ct4dcFnqxwj9r/gF0Etp19pSNM=
|
||||
github.com/tidwall/tinyqueue v0.1.1 h1:SpNEvEggbpyN5DIReaJ2/1ndroY8iyEGxPYxoSaymYE=
|
||||
github.com/tidwall/tinyqueue v0.1.1/go.mod h1:O/QNHwrnjqr6IHItYrzoHAKYhBkLI67Q096fQP5zMYw=
|
||||
github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
|
||||
@@ -627,8 +602,6 @@ golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81R
|
||||
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb h1:eBmm0M9fYhWpKZLjQUUKka/LtIxf46G4fxeEz5KJr9U=
|
||||
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.0.0-20210916014120-12bc252f5db8 h1:/6y1LfuqNuQdHAm0jjtPtgRcxIxjVZgm5OTu8/QhZvk=
|
||||
golang.org/x/net v0.0.0-20210916014120-12bc252f5db8/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
@@ -664,22 +637,14 @@ golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210309074719-68d13333faf2 h1:46ULzRKLh1CwgRq2dC5SlBzEqqNCi8rreOZnNrbqcIY=
|
||||
golang.org/x/sys v0.0.0-20210309074719-68d13333faf2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 h1:XfKQ4OlFl8okEOr5UvAqFRVj8pY/4yfcXrddB8qAbU0=
|
||||
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2 h1:z99zHgr7hKfrUcX/KsoJk5FJfjTceCKIp96+biqP4To=
|
||||
@@ -688,8 +653,6 @@ golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ=
|
||||
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2 h1:+DCIGbF/swA92ohVg0//6X2IVY3KZs6p9mix0ziNYJM=
|
||||
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0 h1:/5xXl8Y5W96D+TtHSlonuFqGHIWVuyCkGJLwGh9JJFs=
|
||||
@@ -771,16 +734,12 @@ gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211207185736-224e4f70c5ad h1:HR3v
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211207185736-224e4f70c5ad/go.mod h1:lUH49SRidDcQGyXPIL9tR2cN3vztcLBo47AqFUgHgIA=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211217193303-c005cce171ac h1:EcXyrTUaQJYiHtLQstXdW04sRH9HwH9mpaxy9Lkcomc=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211217193303-c005cce171ac/go.mod h1:lUH49SRidDcQGyXPIL9tR2cN3vztcLBo47AqFUgHgIA=
|
||||
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220326213923-f323bb71ac8e h1:x58PfjVq6dbYSzM4URM9QfKDKVru1CpngxCM5pGqwbk=
|
||||
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220326213923-f323bb71ac8e/go.mod h1:kIC/Dlp2OjWhVrOkZDN4iEoCaqoac5w1UjpKY6Ftf+U=
|
||||
gopkg.in/macaroon-bakery.v2 v2.0.1/go.mod h1:B4/T17l+ZWGwxFSZQmlBwp25x+og7OkhETfr3S9MbIA=
|
||||
gopkg.in/macaroon.v2 v2.0.0/go.mod h1:+I6LnTMkm/uV5ew/0nsulNjL16SK4+C8yDmRUzHR17I=
|
||||
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=
|
||||
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
|
||||
gopkg.in/telebot.v3 v3.0.0 h1:UgHIiE/RdjoDi6nf4xACM7PU3TqiPVV9vvTydCEnrTo=
|
||||
gopkg.in/telebot.v3 v3.0.0/go.mod h1:7rExV8/0mDDNu9epSrDm/8j22KLaActH1Tbee6YjzWg=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 h1:yiW+nvdHb9LVqSHQBXfZCieqV4fzYhNBql77zY0ykqs=
|
||||
@@ -798,7 +757,6 @@ gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
|
||||
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/sqlite v1.1.4 h1:PDzwYE+sI6De2+mxAneV9Xs11+ZyKV6oxD3wDGkaNvM=
|
||||
gorm.io/driver/sqlite v1.1.4/go.mod h1:mJCeTFr7+crvS+TRnWc5Z3UvwxUN1BGBLMrf5LA9DYw=
|
||||
gorm.io/gorm v1.20.7/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
func dump(r *http.Request) string {
|
||||
x, err := httputil.DumpRequest(r, true)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(x)
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"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: 15 * time.Second,
|
||||
ReadTimeout: 15 * 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) 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
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
<!-- @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}}
|
||||
@@ -1,92 +0,0 @@
|
||||
package userpage
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
"github.com/fiatjaf/go-lnurl"
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
bot *telegram.TipBot
|
||||
}
|
||||
|
||||
func New(b *telegram.TipBot) Service {
|
||||
return Service{
|
||||
bot: b,
|
||||
}
|
||||
}
|
||||
|
||||
const botImage = "https://avatars.githubusercontent.com/u/88730856?v=7"
|
||||
|
||||
//go:embed static
|
||||
var templates embed.FS
|
||||
var tmpl = template.Must(template.ParseFS(templates, "static/userpage.html"))
|
||||
|
||||
var Client = &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
// thank you fiatjaf for this code
|
||||
func (s Service) getTelegramUserPictureURL(username string) (string, error) {
|
||||
// with proxy:
|
||||
// client, err := s.network.GetHttpClient()
|
||||
// if err != nil {
|
||||
// return "", err
|
||||
// }
|
||||
client := http.Client{
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
resp, err := client.Get("https://t.me/" + username)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
doc, err := goquery.NewDocumentFromReader(resp.Body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
url, ok := doc.Find(`meta[property="og:image"]`).First().Attr("content")
|
||||
if !ok {
|
||||
return "", errors.New("no image available for this user")
|
||||
}
|
||||
|
||||
return url, nil
|
||||
}
|
||||
|
||||
func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// https://ln.tips/.well-known/lnurlp/<username>
|
||||
username := strings.ToLower(mux.Vars(r)["username"])
|
||||
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, username)
|
||||
log.Infof("[UserPage] rendering page of %s", username)
|
||||
lnurlEncode, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
log.Errorln("[UserPage]", err)
|
||||
return
|
||||
}
|
||||
image, err := s.getTelegramUserPictureURL(username)
|
||||
if err != nil || image == "https://telegram.org/img/t_logo.png" {
|
||||
// replace the default image
|
||||
image = botImage
|
||||
}
|
||||
|
||||
if err := tmpl.ExecuteTemplate(w, "userpage", struct {
|
||||
Username string
|
||||
Image string
|
||||
LNURLPay string
|
||||
}{username, image, lnurlEncode}); err != nil {
|
||||
log.Errorf("failed to render template")
|
||||
}
|
||||
}
|
||||
@@ -18,12 +18,10 @@ var Configuration = struct {
|
||||
|
||||
type BotConfiguration struct {
|
||||
HttpProxy string `yaml:"http_proxy"`
|
||||
SocksProxy string `yaml:"socks_proxy"`
|
||||
LNURLServer string `yaml:"lnurl_server"`
|
||||
LNURLServerUrl *url.URL `yaml:"-"`
|
||||
LNURLHostName string `yaml:"lnurl_public_host_name"`
|
||||
LNURLHostUrl *url.URL `yaml:"-"`
|
||||
LNURLSendImage bool `yaml:"lnurl_image"`
|
||||
}
|
||||
|
||||
type TelegramConfiguration struct {
|
||||
@@ -35,7 +33,6 @@ type DatabaseConfiguration struct {
|
||||
ShopBuntDbPath string `yaml:"shop_buntdb_path"`
|
||||
BuntDbPath string `yaml:"buntdb_path"`
|
||||
TransactionsPath string `yaml:"transactions_path"`
|
||||
GroupsDbPath string `yaml:"groupsdb_path"`
|
||||
}
|
||||
|
||||
type LnbitsConfiguration struct {
|
||||
|
||||
@@ -9,51 +9,15 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func MigrateAnonIdInt32Hash(db *gorm.DB) error {
|
||||
func MigrateAnonIdHash(db *gorm.DB) error {
|
||||
users := []lnbits.User{}
|
||||
_ = db.Find(&users)
|
||||
for _, u := range users {
|
||||
log.Infof("[MigrateAnonIdInt32Hash] %d -> %d", u.ID, str.Int32Hash(u.ID))
|
||||
log.Info(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("[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)
|
||||
errmsg := fmt.Sprintf("[MigrateAnonIdHash] Error: Couldn't migrate user %s (%d)", u.Telegram.Username, u.Telegram.ID)
|
||||
log.Errorln(errmsg)
|
||||
return tx.Error
|
||||
}
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
package errors
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
import "encoding/json"
|
||||
|
||||
type TipBotErrorType int
|
||||
|
||||
const (
|
||||
DecodeAmountError TipBotErrorType = 1000 + iota
|
||||
DecodePerUserAmountError
|
||||
InvalidAmountError
|
||||
InvalidAmountPerUserError
|
||||
GetBalanceError
|
||||
BalanceToLowError
|
||||
)
|
||||
|
||||
func Create(code TipBotErrorType) TipBotError {
|
||||
return errMap[code]
|
||||
}
|
||||
func New(code TipBotErrorType, err error) TipBotError {
|
||||
if err != nil {
|
||||
return TipBotError{Err: err, Message: err.Error(), Code: code}
|
||||
}
|
||||
return Create(code)
|
||||
return TipBotError{Err: err, Message: err.Error(), Code: code}
|
||||
}
|
||||
|
||||
type TipBotError struct {
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
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")}
|
||||
)
|
||||
@@ -1,9 +1,8 @@
|
||||
package lnbits
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/imroc/req"
|
||||
"time"
|
||||
)
|
||||
|
||||
// NewClient returns a new lnbits api client. Pass your API key and url here.
|
||||
@@ -131,30 +130,6 @@ func (c Client) Info(w Wallet) (wtx Wallet, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// Info 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
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
+11
-77
@@ -1,16 +1,10 @@
|
||||
package lnbits
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/satdress"
|
||||
"github.com/btcsuite/btcd/btcec"
|
||||
|
||||
"github.com/imroc/req"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
@@ -21,31 +15,16 @@ 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 `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_"`
|
||||
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"`
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -118,52 +97,7 @@ type Wallet struct {
|
||||
Name string `json:"name"`
|
||||
User string `json:"user"`
|
||||
}
|
||||
|
||||
type Payments []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 BitInvoice 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(btcec.S256(), 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, err := sk.Sign(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
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
)
|
||||
@@ -54,7 +54,7 @@ func NewServer(bot *telegram.TipBot) *Server {
|
||||
}
|
||||
apiServer := &Server{
|
||||
c: bot.Client,
|
||||
database: bot.DB.Users,
|
||||
database: bot.Database,
|
||||
bot: bot.Telegram,
|
||||
httpServer: srv,
|
||||
buntdb: bot.Bunt,
|
||||
@@ -108,12 +108,8 @@ func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
log.Errorln(err)
|
||||
} else {
|
||||
// do something with the event
|
||||
if c := telegram.InvoiceCallback[txInvoiceEvent.Callback]; c.Function != nil {
|
||||
if err := telegram.AssertEventType(txInvoiceEvent, c.Type); err != nil {
|
||||
log.Errorln(err)
|
||||
return
|
||||
}
|
||||
c.Function(txInvoiceEvent)
|
||||
if c := telegram.InvoiceCallback[txInvoiceEvent.Callback]; c != nil {
|
||||
c(txInvoiceEvent)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
package lndhub
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/api"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
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) {
|
||||
auth := request.Header.Get("Authorization")
|
||||
|
||||
// check if the user is banned
|
||||
if auth != "" {
|
||||
_, password, ok := parseBearerAuth(auth)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// first we make sure that the password is not already "banned_"
|
||||
if strings.Contains(password, "_") || strings.HasPrefix(password, "banned_") {
|
||||
log.Warnf("[LNDHUB] Banned user %s. Not forwarding request", password)
|
||||
return
|
||||
}
|
||||
// then we check whether the "normal" password provided is in the database (it should be not if the user is banned)
|
||||
user := &lnbits.User{}
|
||||
tx := w.database.Where("wallet_adminkey = ? COLLATE NOCASE", password).First(user)
|
||||
if tx.Error != nil {
|
||||
log.Warnf("[LNDHUB] Could not get wallet admin key %s: %v", password, tx.Error)
|
||||
return
|
||||
}
|
||||
log.Debugf("[LNDHUB] User: %s", telegram.GetUserStr(user.Telegram))
|
||||
}
|
||||
// if not, proxy the request
|
||||
api.Proxy(writer, request, internal.Configuration.Lnbits.Url)
|
||||
}
|
||||
|
||||
// parseBearerAuth parses an HTTP Basic Authentication string.
|
||||
// "Bearer QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
|
||||
func parseBearerAuth(auth string) (username, password string, ok bool) {
|
||||
const prefix = "Bearer "
|
||||
// Case insensitive prefix match. See Issue 22736.
|
||||
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
|
||||
return
|
||||
}
|
||||
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
cs := string(c)
|
||||
s := strings.IndexByte(cs, ':')
|
||||
if s < 0 {
|
||||
return
|
||||
}
|
||||
return cs[:s], cs[s+1:], true
|
||||
}
|
||||
+48
-210
@@ -3,22 +3,12 @@ package lnurl
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"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"
|
||||
@@ -27,49 +17,20 @@ import (
|
||||
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 {
|
||||
type LNURLInvoice struct {
|
||||
*telegram.Invoice
|
||||
Comment string `json:"comment"`
|
||||
User *lnbits.User `json:"user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Paid bool `json:"paid"`
|
||||
PaidAt time.Time `json:"paid_at"`
|
||||
From string `json:"from"`
|
||||
}
|
||||
type Lnurl struct {
|
||||
telegram *tb.Bot
|
||||
c *lnbits.Client
|
||||
database *gorm.DB
|
||||
callbackHostname *url.URL
|
||||
buntdb *storage.DB
|
||||
WebhookServer string
|
||||
cache telegram.Cache
|
||||
}
|
||||
|
||||
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 {
|
||||
func (lnurlInvoice LNURLInvoice) Key() string {
|
||||
return fmt.Sprintf("lnurl-p:%s", lnurlInvoice.PaymentHash)
|
||||
}
|
||||
|
||||
func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
|
||||
func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
|
||||
var err error
|
||||
var response interface{}
|
||||
username := mux.Vars(request)["username"]
|
||||
@@ -78,31 +39,20 @@ func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
|
||||
} else {
|
||||
stringAmount := request.FormValue("amount")
|
||||
if stringAmount == "" {
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Form value 'amount' is not set"))
|
||||
NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Form value 'amount' is not set"))
|
||||
return
|
||||
}
|
||||
amount, parseError := strconv.Atoi(stringAmount)
|
||||
if parseError != nil {
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int %v", parseError))
|
||||
NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int %v", parseError))
|
||||
return
|
||||
}
|
||||
comment := request.FormValue("comment")
|
||||
if len(comment) > CommentAllowed {
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Comment is too long"))
|
||||
NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Comment is too long"))
|
||||
return
|
||||
}
|
||||
|
||||
// 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))
|
||||
fmt.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err)
|
||||
fmt.Errorf("[handleLnUrl] payerdata: %v", payerdata)
|
||||
}
|
||||
|
||||
response, err = w.serveLNURLpSecond(username, int64(amount), comment, payerData)
|
||||
response, err = w.serveLNURLpSecond(username, int64(amount), comment)
|
||||
}
|
||||
// check if error was returned from first or second handlers
|
||||
if err != nil {
|
||||
@@ -110,103 +60,85 @@ func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
|
||||
log.Errorf("[LNURL] %v", err.Error())
|
||||
if response != nil {
|
||||
// there is a valid error response
|
||||
err = api.WriteResponse(writer, response)
|
||||
err = writeResponse(writer, response)
|
||||
if err != nil {
|
||||
api.NotFoundHandler(writer, err)
|
||||
NotFoundHandler(writer, err)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
// no error from first or second handler
|
||||
err = api.WriteResponse(writer, response)
|
||||
err = writeResponse(writer, response)
|
||||
if err != nil {
|
||||
api.NotFoundHandler(writer, err)
|
||||
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 Lnurl) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error) {
|
||||
func (w Server) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error) {
|
||||
log.Infof("[LNURL] Serving endpoint for user %s", username)
|
||||
callbackURL, err := url.Parse(fmt.Sprintf("%s/%s/%s", w.callbackHostname.String(), Endpoint, username))
|
||||
callbackURL, err := url.Parse(fmt.Sprintf("%s/%s/%s", w.callbackHostname.String(), lnurlEndpoint, username))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// produce the metadata including the image
|
||||
metadata := w.getMetaDataCached(username)
|
||||
metadata := w.metaData(username)
|
||||
|
||||
return &lnurl.LNURLPayParams{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: api.StatusOk},
|
||||
Tag: PayRequestTag,
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: statusOk},
|
||||
Tag: payRequestTag,
|
||||
Callback: callbackURL.String(),
|
||||
MinSendable: MinSendable,
|
||||
MinSendable: minSendable,
|
||||
MaxSendable: MaxSendable,
|
||||
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 Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment string, payerData lnurl.PayerDataValues) (*lnurl.LNURLPayValues, error) {
|
||||
func (w Server) serveLNURLpSecond(username string, amount_msat int64, comment string) (*lnurl.LNURLPayValues, error) {
|
||||
log.Infof("[LNURL] Serving invoice for user %s", username)
|
||||
if amount_msat < MinSendable || amount_msat > MaxSendable {
|
||||
if amount_msat < minSendable || amount_msat > MaxSendable {
|
||||
// amount is not ok
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.StatusError,
|
||||
Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", MinSendable, MinSendable)},
|
||||
Status: statusError,
|
||||
Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", minSendable, MaxSendable)},
|
||||
}, fmt.Errorf("amount out of bounds")
|
||||
}
|
||||
// check comment length
|
||||
if len(comment) > CommentAllowed {
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.StatusError,
|
||||
Status: statusError,
|
||||
Reason: fmt.Sprintf("Comment too long (max: %d characters).", CommentAllowed)},
|
||||
}, fmt.Errorf("comment too long")
|
||||
}
|
||||
user, tx := findUser(w.database, username)
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
if tx.Error != nil {
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.StatusError,
|
||||
Status: statusError,
|
||||
Reason: fmt.Sprintf("Invalid user.")},
|
||||
}, fmt.Errorf("[GetUser] Couldn't fetch user info from database: %v", tx.Error)
|
||||
}
|
||||
if user.Wallet == nil {
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.StatusError,
|
||||
Status: statusError,
|
||||
Reason: fmt.Sprintf("Invalid user.")},
|
||||
}, fmt.Errorf("[serveLNURLpSecond] user %s not found", username)
|
||||
}
|
||||
@@ -216,24 +148,11 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
|
||||
var resp *lnurl.LNURLPayValues
|
||||
|
||||
// the same description_hash needs to be built in the second request
|
||||
metadata := w.getMetaDataCached(username)
|
||||
|
||||
var payerDataByte []byte
|
||||
var err error
|
||||
if payerData.Email != "" || payerData.LightningAddress != "" || payerData.FreeName != "" {
|
||||
payerDataByte, err = json.Marshal(payerData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
payerDataByte = []byte("")
|
||||
}
|
||||
|
||||
descriptionHash, err := w.descriptionHash(metadata, string(payerDataByte))
|
||||
metadata := w.metaData(username)
|
||||
descriptionHash, err := w.descriptionHash(metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Amount: amount_msat / 1000,
|
||||
@@ -245,7 +164,7 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
|
||||
err = fmt.Errorf("[serveLNURLpSecond] Couldn't create invoice: %v", err.Error())
|
||||
resp = &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.StatusError,
|
||||
Status: statusError,
|
||||
Reason: "Couldn't create invoice."},
|
||||
}
|
||||
return resp, err
|
||||
@@ -255,14 +174,13 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
|
||||
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)
|
||||
// save lnurl invoice struct for later use (will hold the comment or other metdata for a notification when paid)
|
||||
runtime.IgnoreError(w.buntdb.Set(
|
||||
Invoice{
|
||||
LNURLInvoice{
|
||||
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(
|
||||
@@ -273,7 +191,7 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
|
||||
}))
|
||||
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: api.StatusOk},
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: statusOk},
|
||||
PR: invoice.PaymentRequest,
|
||||
Routes: make([]struct{}, 0),
|
||||
SuccessAction: &lnurl.SuccessAction{Message: "Payment received!", Tag: "message"},
|
||||
@@ -282,97 +200,17 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
|
||||
}
|
||||
|
||||
// descriptionHash is the SHA256 hash of the metadata
|
||||
func (w Lnurl) descriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
|
||||
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[:])
|
||||
}
|
||||
func (w Server) descriptionHash(metadata lnurl.Metadata) (string, error) {
|
||||
hash := sha256.Sum256([]byte(metadata.Encode()))
|
||||
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 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
|
||||
}
|
||||
}
|
||||
|
||||
func (w Server) metaData(username string) lnurl.Metadata {
|
||||
return lnurl.Metadata{
|
||||
Description: fmt.Sprintf("Pay to %s@%s", username, w.callbackHostname.Hostname()),
|
||||
LightningAddress: fmt.Sprintf("%s@%s", username, w.callbackHostname.Hostname()),
|
||||
}
|
||||
}
|
||||
|
||||
// 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 ""
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
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
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package network
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
func GetHttpClient() (*http.Client, error) {
|
||||
client := http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
if internal.Configuration.Bot.HttpProxy != "" {
|
||||
proxyUrl, err := url.Parse(internal.Configuration.Bot.HttpProxy)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return nil, err
|
||||
}
|
||||
client.Transport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)}
|
||||
}
|
||||
return &client, nil
|
||||
}
|
||||
func GetSocksClient() (*http.Client, error) {
|
||||
client := http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
if internal.Configuration.Bot.SocksProxy != "" {
|
||||
proxyURL, _ := url.Parse(internal.Configuration.Bot.SocksProxy)
|
||||
specialTransport := &http.Transport{}
|
||||
specialTransport.Proxy = http.ProxyURL(proxyURL)
|
||||
d, err := proxy.SOCKS5("tcp", internal.Configuration.Bot.SocksProxy, nil, &net.Dialer{
|
||||
Timeout: 20 * time.Second,
|
||||
Deadline: time.Now().Add(time.Second * 10),
|
||||
KeepAlive: -1,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return &client, nil
|
||||
}
|
||||
specialTransport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return d.Dial(network, addr)
|
||||
}
|
||||
client.Transport = specialTransport
|
||||
}
|
||||
return &client, nil
|
||||
}
|
||||
@@ -2,12 +2,11 @@ package rate
|
||||
|
||||
import (
|
||||
"context"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"golang.org/x/time/rate"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
// Limiter
|
||||
@@ -23,7 +22,7 @@ var globalLimiter *rate.Limiter
|
||||
|
||||
// NewLimiter creates both chat and global rate limiters.
|
||||
func Start() {
|
||||
idLimiter = newIdRateLimiter(rate.Limit(0.29), 19)
|
||||
idLimiter = newIdRateLimiter(rate.Limit(0.25), 20)
|
||||
globalLimiter = rate.NewLimiter(rate.Limit(30), 30)
|
||||
}
|
||||
|
||||
@@ -43,8 +42,6 @@ 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:
|
||||
@@ -57,11 +54,8 @@ func CheckLimit(to interface{}) {
|
||||
}
|
||||
}
|
||||
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,
|
||||
|
||||
@@ -3,39 +3,16 @@ 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.
|
||||
@@ -56,12 +33,6 @@ func checkSoftLock(s string) int {
|
||||
// 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))
|
||||
@@ -82,26 +53,17 @@ func LockWithContext(ctx context.Context, s string) {
|
||||
// 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))
|
||||
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.
|
||||
@@ -111,31 +73,23 @@ 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)
|
||||
log.Errorf("[Mutex] ⚠⚠⚠️ Unlock %s not in mutexMap. Skip.", s)
|
||||
}
|
||||
mutexMapSync.Unlock()
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ func Once(k1, k2 string) error {
|
||||
// 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)
|
||||
return fmt.Errorf("%s already consumed object", k2)
|
||||
}
|
||||
objectMap.Set(k2, true)
|
||||
return nil
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -1,345 +0,0 @@
|
||||
package satdress
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/network"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
"golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
// Much of this is from github.com/fiatjaf/makeinvoice
|
||||
// but with added "checkInvoice" and http proxy support
|
||||
|
||||
var Client, _ = network.GetSocksClient()
|
||||
|
||||
type LNDParams struct {
|
||||
Cert []byte `json:"cert" gorm:"-"`
|
||||
CertString string `json:"certstring"`
|
||||
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) {
|
||||
specialTransport := &http.Transport{}
|
||||
|
||||
// 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")
|
||||
}
|
||||
specialTransport.TLSClientConfig = &tls.Config{RootCAs: caCertPool}
|
||||
} else {
|
||||
specialTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
|
||||
}
|
||||
|
||||
// use a proxy?
|
||||
var HttpProxyURL = internal.Configuration.Bot.SocksProxy
|
||||
if useProxy && len(HttpProxyURL) > 0 {
|
||||
proxyURL, _ := url.Parse(HttpProxyURL)
|
||||
specialTransport.Proxy = http.ProxyURL(proxyURL)
|
||||
d, err := proxy.SOCKS5("tcp", HttpProxyURL, nil, &net.Dialer{
|
||||
Timeout: 20 * time.Second,
|
||||
Deadline: time.Now().Add(time.Second * 10),
|
||||
KeepAlive: -1,
|
||||
})
|
||||
if err != nil {
|
||||
return Client, err
|
||||
}
|
||||
specialTransport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return d.Dial(network, addr)
|
||||
}
|
||||
}
|
||||
Client.Transport = specialTransport
|
||||
return Client, nil
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"time"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
@@ -88,6 +87,5 @@ func (tx *Base) Set(s Storable, db *DB) error {
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
package str
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
)
|
||||
|
||||
var markdownV2Escapes = []string{"_", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!"}
|
||||
@@ -41,17 +38,3 @@ func Int64Hash(s string) uint64 {
|
||||
h.Write([]byte(s))
|
||||
return h.Sum64()
|
||||
}
|
||||
|
||||
func AnonIdSha256(u *lnbits.User) string {
|
||||
h := sha256.Sum256([]byte(u.Wallet.ID))
|
||||
hash := fmt.Sprintf("%x", h)
|
||||
anon_id := fmt.Sprintf("0x%s", hash[:16]) // starts with 0x because that can't be a valid telegram username
|
||||
return anon_id
|
||||
}
|
||||
|
||||
func UUIDSha256(u *lnbits.User) string {
|
||||
h := sha256.Sum256([]byte(u.Wallet.ID))
|
||||
hash := fmt.Sprintf("%x", h)
|
||||
anon_id := fmt.Sprintf("1x%s", hash[len(hash)-16:]) // starts with 1x because that can't be a valid telegram username
|
||||
return anon_id
|
||||
}
|
||||
|
||||
@@ -3,13 +3,11 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
@@ -17,12 +15,12 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/price"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func getArgumentFromCommand(input string, which int) (output string, err error) {
|
||||
if len(strings.Split(input, " ")) < which+1 {
|
||||
return "", fmt.Errorf("message doesn't contain enough arguments")
|
||||
return "", errors.New("message doesn't contain enough arguments")
|
||||
}
|
||||
output = strings.Split(input, " ")[which]
|
||||
return output, nil
|
||||
@@ -32,7 +30,7 @@ func decodeAmountFromCommand(input string) (amount int64, err error) {
|
||||
if len(strings.Split(input, " ")) < 2 {
|
||||
errmsg := "message doesn't contain any amount"
|
||||
// log.Errorln(errmsg)
|
||||
return 0, fmt.Errorf(errmsg)
|
||||
return 0, errors.New(errmsg)
|
||||
}
|
||||
amount, err = getAmount(strings.Split(input, " ")[1])
|
||||
return amount, err
|
||||
@@ -63,7 +61,7 @@ func getAmount(input string) (amount int64, err error) {
|
||||
return 0, err
|
||||
}
|
||||
if !(price.Price[currency] > 0) {
|
||||
return 0, fmt.Errorf("price is zero")
|
||||
return 0, errors.New("price is zero")
|
||||
}
|
||||
amount = int64(fmount / price.Price[currency] * float64(100_000_000))
|
||||
return amount, nil
|
||||
@@ -76,7 +74,7 @@ func getAmount(input string) (amount int64, err error) {
|
||||
return 0, err
|
||||
}
|
||||
if amount <= 0 {
|
||||
return 0, fmt.Errorf("amount must be greater than 0")
|
||||
return 0, errors.New("amount must be greater than 0")
|
||||
}
|
||||
return amount, err
|
||||
}
|
||||
@@ -121,15 +119,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 intercept.Context) (intercept.Context, error) {
|
||||
func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return // errors.New("user has no wallet"), 0
|
||||
}
|
||||
|
||||
if !(user.StateKey == lnbits.UserEnterAmount) {
|
||||
ResetUserState(user, bot)
|
||||
return ctx, fmt.Errorf("invalid statekey")
|
||||
return // errors.New("user state does not match"), 0
|
||||
}
|
||||
|
||||
var EnterAmountStateData EnterAmountStateData
|
||||
@@ -137,24 +135,24 @@ func (bot *TipBot) enterAmountHandler(ctx intercept.Context) (intercept.Context,
|
||||
if err != nil {
|
||||
log.Errorf("[enterAmountHandler] %s", err.Error())
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
amount, err := getAmount(ctx.Message().Text)
|
||||
amount, err := getAmount(m.Text)
|
||||
if err != nil {
|
||||
log.Warnf("[enterAmountHandler] %s", err.Error())
|
||||
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
return //err, 0
|
||||
}
|
||||
// amount not in allowed range from LNURL
|
||||
if EnterAmountStateData.AmountMin > 0 && EnterAmountStateData.AmountMax >= EnterAmountStateData.AmountMin && // this line checks whether min_max is set at all
|
||||
(amount > int64(EnterAmountStateData.AmountMax/1000) || amount < int64(EnterAmountStateData.AmountMin/1000)) { // this line then checks whether the amount is in the range
|
||||
err = fmt.Errorf("amount not in range")
|
||||
log.Warnf("[enterAmountHandler] %s", err.Error())
|
||||
bot.trySendMessage(ctx.Sender(), fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), EnterAmountStateData.AmountMin/1000, EnterAmountStateData.AmountMax/1000))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), EnterAmountStateData.AmountMin/1000, EnterAmountStateData.AmountMax/1000))
|
||||
ResetUserState(user, bot)
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
return
|
||||
}
|
||||
|
||||
// find out which type the object in bunt has waiting for an amount
|
||||
@@ -166,7 +164,7 @@ func (bot *TipBot) enterAmountHandler(ctx intercept.Context) (intercept.Context,
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
LnurlPayState := sn.(*LnurlPayState)
|
||||
LnurlPayState.Amount = amount * 1000 // mSat
|
||||
@@ -177,17 +175,18 @@ func (bot *TipBot) enterAmountHandler(ctx intercept.Context) (intercept.Context,
|
||||
StateDataJson, err := json.Marshal(EnterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
|
||||
return bot.lnurlPayHandlerSend(ctx)
|
||||
bot.lnurlPayHandlerSend(ctx, m)
|
||||
return
|
||||
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
|
||||
return
|
||||
}
|
||||
LnurlWithdrawState := sn.(*LnurlWithdrawState)
|
||||
LnurlWithdrawState.Amount = amount * 1000 // mSat
|
||||
@@ -198,28 +197,35 @@ func (bot *TipBot) enterAmountHandler(ctx intercept.Context) (intercept.Context,
|
||||
StateDataJson, err := json.Marshal(EnterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
|
||||
return bot.lnurlWithdrawHandlerWithdraw(ctx)
|
||||
bot.lnurlWithdrawHandlerWithdraw(ctx, m)
|
||||
return
|
||||
case "CreateInvoiceState":
|
||||
ctx.Message().Text = fmt.Sprintf("/invoice %d", amount)
|
||||
m.Text = fmt.Sprintf("/invoice %d", amount)
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
return bot.invoiceHandler(ctx)
|
||||
bot.invoiceHandler(ctx, m)
|
||||
return
|
||||
case "CreateDonationState":
|
||||
ctx.Message().Text = fmt.Sprintf("/donate %d", amount)
|
||||
m.Text = fmt.Sprintf("/donate %d", amount)
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
return bot.donationHandler(ctx)
|
||||
bot.donationHandler(ctx, m)
|
||||
return
|
||||
case "CreateSendState":
|
||||
splits := strings.SplitAfterN(EnterAmountStateData.OiringalCommand, " ", 2)
|
||||
if len(splits) > 1 {
|
||||
ctx.Message().Text = fmt.Sprintf("/send %d %s", amount, splits[1])
|
||||
m.Text = fmt.Sprintf("/send %d %s", amount, splits[1])
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
return bot.sendHandler(ctx)
|
||||
bot.sendHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
return
|
||||
default:
|
||||
ResetUserState(user, bot)
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
return
|
||||
}
|
||||
// // reset database entry
|
||||
// ResetUserState(user, bot)
|
||||
// return
|
||||
}
|
||||
|
||||
@@ -1,22 +1,17 @@
|
||||
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/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot *TipBot) balanceHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
func (bot TipBot) balanceHandler(ctx context.Context, m *tb.Message) {
|
||||
// check and print all commands
|
||||
if len(m.Text) > 0 {
|
||||
bot.anyTextHandler(ctx)
|
||||
}
|
||||
|
||||
bot.anyTextHandler(ctx, m)
|
||||
// reply only in private message
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
@@ -25,22 +20,23 @@ func (bot *TipBot) balanceHandler(ctx intercept.Context) (intercept.Context, err
|
||||
// first check whether the user is initialized
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
|
||||
if !user.Initialized {
|
||||
return bot.startHandler(ctx)
|
||||
bot.startHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
usrStr := GetUserStr(ctx.Sender())
|
||||
usrStr := GetUserStr(m.Sender)
|
||||
balance, err := bot.GetUserBalance(user)
|
||||
if err != nil {
|
||||
log.Errorf("[/balance] Error fetching %s's balance: %s", usrStr, err)
|
||||
bot.trySendMessage(ctx.Sender(), Translate(ctx, "balanceErrorMessage"))
|
||||
return ctx, err
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "balanceErrorMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[/balance] %s's balance: %d sat\n", usrStr, balance)
|
||||
bot.trySendMessage(ctx.Sender(), fmt.Sprintf(Translate(ctx, "balanceMessage"), balance))
|
||||
return ctx, nil
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "balanceMessage"), balance))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -2,14 +2,9 @@ package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"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"
|
||||
@@ -19,13 +14,15 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
gocache "github.com/patrickmn/go-cache"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type TipBot struct {
|
||||
DB *Databases
|
||||
Database *gorm.DB
|
||||
Bunt *storage.DB
|
||||
ShopBunt *storage.DB
|
||||
logger *gorm.DB
|
||||
Telegram *tb.Bot
|
||||
Client *lnbits.Client
|
||||
limiter map[string]limiter.Limiter
|
||||
@@ -45,11 +42,12 @@ func NewBot() TipBot {
|
||||
gocacheClient := gocache.New(5*time.Minute, 10*time.Minute)
|
||||
gocacheStore := store.NewGoCache(gocacheClient, nil)
|
||||
// create sqlite databases
|
||||
dbs := AutoMigration()
|
||||
db, txLogger := AutoMigration()
|
||||
limiter.Start()
|
||||
return TipBot{
|
||||
DB: dbs,
|
||||
Database: db,
|
||||
Client: lnbits.NewClient(internal.Configuration.Lnbits.AdminKey, internal.Configuration.Lnbits.Url),
|
||||
logger: txLogger,
|
||||
Bunt: createBunt(internal.Configuration.Database.BuntDbPath),
|
||||
ShopBunt: createBunt(internal.Configuration.Database.ShopBuntDbPath),
|
||||
Telegram: newTelegramBot(),
|
||||
@@ -83,29 +81,6 @@ 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() {
|
||||
log.Infof("[Telegram] Authorized on account @%s", bot.Telegram.Me.Username)
|
||||
@@ -114,31 +89,8 @@ func (bot *TipBot) Start() {
|
||||
if err != nil {
|
||||
log.Errorf("Could not initialize bot wallet: %s", err.Error())
|
||||
}
|
||||
|
||||
// register telegram handlers
|
||||
bot.registerTelegramHandlers()
|
||||
|
||||
// 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()
|
||||
bot.Telegram.Start()
|
||||
}
|
||||
|
||||
+12
-104
@@ -1,39 +1,27 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
import tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
|
||||
// we can't use space in the label of buttons, because string splitting will mess everything up.
|
||||
const (
|
||||
MainMenuCommandSend = "💸 Send"
|
||||
MainMenuCommandBalance = "Balance"
|
||||
MainMenuCommandInvoice = "⚡️ Invoice"
|
||||
MainMenuCommandHelp = "📖 Help"
|
||||
SendMenuCommandEnter = "👤 Enter"
|
||||
CommandSend = "💸 Send"
|
||||
CommandBalance = "👑 Balance"
|
||||
CommandInvoice = "⚡️ Invoice"
|
||||
CommandHelp = "📖 Help"
|
||||
)
|
||||
|
||||
var (
|
||||
mainMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnHelpMainMenu = mainMenu.Text(MainMenuCommandHelp)
|
||||
btnSendMainMenu = mainMenu.Text(MainMenuCommandSend)
|
||||
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
|
||||
btnInvoiceMainMenu = mainMenu.Text(MainMenuCommandInvoice)
|
||||
|
||||
sendToMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
sendToButtons = []tb.Btn{}
|
||||
btnSendMenuEnter = mainMenu.Text(SendMenuCommandEnter)
|
||||
mainMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnHelpMainMenu = mainMenu.Text(CommandHelp)
|
||||
btnSendMainMenu = mainMenu.Text(CommandSend)
|
||||
btnBalanceMainMenu = mainMenu.Text(CommandBalance)
|
||||
btnInvoiceMainMenu = mainMenu.Text(CommandInvoice)
|
||||
)
|
||||
|
||||
func init() {
|
||||
mainMenu.Reply(
|
||||
mainMenu.Row(btnBalanceMainMenu),
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu, btnHelpMainMenu),
|
||||
mainMenu.Row(btnBalanceMainMenu, btnHelpMainMenu),
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -57,83 +45,3 @@ func buttonWrapper(buttons []tb.Btn, markup *tb.ReplyMarkup, length int) []tb.Ro
|
||||
rows = append(rows, markup.Row(buttons...))
|
||||
return rows
|
||||
}
|
||||
|
||||
// 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)
|
||||
mainMenu.Reply(
|
||||
mainMenu.Row(btnBalanceMainMenu),
|
||||
mainMenu.Row(btnInvoiceMainMenu, 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: fmt.Sprintf("%s", 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
|
||||
}
|
||||
|
||||
+10
-124
@@ -1,18 +1,11 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
@@ -23,17 +16,11 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
"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:*"
|
||||
@@ -52,47 +39,21 @@ func createBunt(file string) *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 anon_id database migrations ...")
|
||||
log.Info("Running ano_id database migrations ...")
|
||||
// run the migration on anon_id
|
||||
err = database.MigrateAnonIdInt32Hash(db)
|
||||
err = database.MigrateAnonIdHash(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() *Databases {
|
||||
func AutoMigration() (db *gorm.DB, txLogger *gorm.DB) {
|
||||
orm, err := gorm.Open(sqlite.Open(internal.Configuration.Database.DbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
if err != nil {
|
||||
panic("Initialize orm failed.")
|
||||
@@ -106,7 +67,7 @@ func AutoMigration() *Databases {
|
||||
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.")
|
||||
}
|
||||
@@ -114,21 +75,7 @@ func AutoMigration() *Databases {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
return orm, txLogger
|
||||
}
|
||||
|
||||
func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.User, error) {
|
||||
@@ -137,7 +84,7 @@ func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.U
|
||||
if len(toUserStrWithoutAt) > 100 {
|
||||
return nil, fmt.Errorf("[GetUserByTelegramUsername] Telegram username is too long: %s..", toUserStrWithoutAt[:100])
|
||||
}
|
||||
tx := bot.DB.Users.Where("telegram_username = ? COLLATE NOCASE", toUserStrWithoutAt).First(toUserDb)
|
||||
tx := bot.Database.Where("telegram_username = ? COLLATE NOCASE", toUserStrWithoutAt).First(toUserDb)
|
||||
if tx.Error != nil || toUserDb.Wallet == nil {
|
||||
err := tx.Error
|
||||
if toUserDb.Wallet == nil {
|
||||
@@ -164,7 +111,7 @@ func getCachedUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
// without updating the user in storage.
|
||||
func GetLnbitsUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
|
||||
tx := bot.DB.Users.First(user)
|
||||
tx := bot.Database.First(user)
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[GetUser] Couldn't fetch %s from Database: %s", GetUserStr(u), tx.Error.Error())
|
||||
log.Warnln(errmsg)
|
||||
@@ -175,21 +122,6 @@ 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
|
||||
@@ -222,62 +154,16 @@ 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()
|
||||
|
||||
// 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)
|
||||
tx := bot.Database.Save(user)
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[UpdateUserRecord] Error: Couldn't update %s's info in Database.", GetUserStr(user.Telegram))
|
||||
log.Errorln(errmsg)
|
||||
return tx.Error
|
||||
}
|
||||
log.Tracef("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
|
||||
log.Debugf("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
|
||||
if bot.Cache.GoCacheStore != nil {
|
||||
updateCachedUser(user, bot)
|
||||
}
|
||||
|
||||
+15
-24
@@ -3,19 +3,16 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"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/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
// PLEASE DO NOT CHANGE THE CODE IN THIS FILE
|
||||
@@ -35,36 +32,35 @@ func helpDonateUsage(ctx context.Context, errormsg string) string {
|
||||
}
|
||||
}
|
||||
|
||||
func (bot TipBot) donationHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) {
|
||||
// check and print all commands
|
||||
m := ctx.Message()
|
||||
bot.anyTextHandler(ctx)
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
// 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
|
||||
_, err = bot.askForAmount(ctx, "", "CreateDonationState", 0, 0, m.Text)
|
||||
return ctx, err
|
||||
bot.askForAmount(ctx, "", "CreateDonationState", 0, 0, m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// command is valid
|
||||
msg := bot.trySendMessageEditable(m.Chat, Translate(ctx, "donationProgressMessage"))
|
||||
msg := bot.trySendMessage(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 ctx, err
|
||||
return
|
||||
}
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
// send donation invoice
|
||||
@@ -76,14 +72,10 @@ func (bot TipBot) donationHandler(ctx intercept.Context) (intercept.Context, err
|
||||
errmsg := fmt.Sprintf("[/donate] Donation failed for user %s: %s", userStr, err)
|
||||
log.Errorln(errmsg)
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
// 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
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationSuccess"))
|
||||
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -120,8 +112,7 @@ func (rot13 rot13Reader) Read(b []byte) (int, error) {
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (bot TipBot) parseCmdDonHandler(ctx intercept.Context) error {
|
||||
m := ctx.Message()
|
||||
func (bot TipBot) parseCmdDonHandler(ctx context.Context, m *tb.Message) error {
|
||||
arg := ""
|
||||
if strings.HasPrefix(strings.ToLower(m.Text), "/send") {
|
||||
arg, _ = getArgumentFromCommand(m.Text, 2)
|
||||
@@ -153,7 +144,7 @@ func (bot TipBot) parseCmdDonHandler(ctx intercept.Context) error {
|
||||
|
||||
bot.trySendMessage(m.Sender, str.MarkdownEscape(donationInterceptMessage))
|
||||
m.Text = fmt.Sprintf("/donate %d", amount)
|
||||
bot.donationHandler(ctx)
|
||||
// returning nil here will abort the parent ctx (/pay or /tip)
|
||||
bot.donationHandler(ctx, m)
|
||||
// returning nil here will abort the parent handler (/pay or /tip)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
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()))
|
||||
}
|
||||
@@ -1,34 +1,32 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"context"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot *TipBot) fileHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
func (bot *TipBot) fileHandler(ctx context.Context, m *tb.Message) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
return
|
||||
}
|
||||
user := LoadUser(ctx)
|
||||
if c := stateCallbackMessage[user.StateKey]; c != nil {
|
||||
// found ctx for this state
|
||||
// found handler 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)
|
||||
bot.shopViewDeleteAllStatusMsgs(ctx, user, 0)
|
||||
runtime.RemoveTicker(user.ID)
|
||||
})
|
||||
} else {
|
||||
ticker.ResetChan <- struct{}{}
|
||||
}
|
||||
|
||||
return c(ctx)
|
||||
c(ctx, m)
|
||||
return
|
||||
}
|
||||
return ctx, errors.Create(errors.NoFileFoundError)
|
||||
}
|
||||
|
||||
@@ -1,481 +0,0 @@
|
||||
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"), GetUserStr(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, GetUserStr(ticketEvent.Payer.Telegram)))
|
||||
} else {
|
||||
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoice"), ticketSat, ticketEvent.Group.Title, GetUserStr(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
|
||||
}
|
||||
+100
-247
@@ -1,17 +1,18 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type InterceptionWrapper struct {
|
||||
type Handler struct {
|
||||
Endpoints []interface{}
|
||||
Handler intercept.Func
|
||||
Handler interface{}
|
||||
Interceptor *Interceptor
|
||||
}
|
||||
|
||||
@@ -20,7 +21,7 @@ func (bot TipBot) registerTelegramHandlers() {
|
||||
telegramHandlerRegistration.Do(func() {
|
||||
// Set up handlers
|
||||
for _, h := range bot.getHandler() {
|
||||
log.Traceln("registering", h.Endpoints)
|
||||
log.Debugln("registering", h.Endpoints)
|
||||
bot.register(h)
|
||||
}
|
||||
|
||||
@@ -37,22 +38,40 @@ func getDefaultAfterInterceptor(bot TipBot) []intercept.Func {
|
||||
return []intercept.Func{}
|
||||
}
|
||||
|
||||
// registerHandlerWithInterceptor will register a ctx with all the predefined interceptors, based on the interceptor type
|
||||
func (bot TipBot) registerHandlerWithInterceptor(h InterceptionWrapper) {
|
||||
// registerHandlerWithInterceptor will register a handler with all the predefined interceptors, based on the interceptor type
|
||||
func (bot TipBot) registerHandlerWithInterceptor(h Handler) {
|
||||
h.Interceptor.Before = append(getDefaultBeforeInterceptor(bot), h.Interceptor.Before...)
|
||||
//h.Interceptor.After = append(h.Interceptor.After, getDefaultAfterInterceptor(bot)...)
|
||||
//h.Interceptor.OnDefer = append(h.Interceptor.OnDefer, getDefaultDeferInterceptor(bot)...)
|
||||
for _, endpoint := range h.Endpoints {
|
||||
bot.handle(endpoint, intercept.WithHandler(h.Handler,
|
||||
intercept.WithBefore(h.Interceptor.Before...),
|
||||
intercept.WithAfter(h.Interceptor.After...),
|
||||
intercept.WithDefer(h.Interceptor.OnDefer...)))
|
||||
|
||||
switch h.Interceptor.Type {
|
||||
case MessageInterceptor:
|
||||
for _, endpoint := range h.Endpoints {
|
||||
bot.handle(endpoint, intercept.HandlerWithMessage(h.Handler.(func(ctx context.Context, query *tb.Message)),
|
||||
intercept.WithBeforeMessage(h.Interceptor.Before...),
|
||||
intercept.WithAfterMessage(h.Interceptor.After...),
|
||||
intercept.WithDeferMessage(h.Interceptor.OnDefer...)))
|
||||
}
|
||||
case QueryInterceptor:
|
||||
for _, endpoint := range h.Endpoints {
|
||||
bot.handle(endpoint, intercept.HandlerWithQuery(h.Handler.(func(ctx context.Context, query *tb.Query)),
|
||||
intercept.WithBeforeQuery(h.Interceptor.Before...),
|
||||
intercept.WithAfterQuery(h.Interceptor.After...),
|
||||
intercept.WithDeferQuery(h.Interceptor.OnDefer...)))
|
||||
}
|
||||
case CallbackInterceptor:
|
||||
for _, endpoint := range h.Endpoints {
|
||||
bot.handle(endpoint, intercept.HandlerWithCallback(h.Handler.(func(ctx context.Context, callback *tb.Callback)),
|
||||
intercept.WithBeforeCallback(h.Interceptor.Before...),
|
||||
intercept.WithAfterCallback(append(h.Interceptor.After, bot.answerCallbackInterceptor)...),
|
||||
intercept.WithDeferCallback(h.Interceptor.OnDefer...)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handle accepts an endpoint and handler for Telegram handler registration.
|
||||
// function will automatically register string handlers as uppercase and first letter uppercase.
|
||||
func (bot TipBot) handle(endpoint interface{}, handler tb.HandlerFunc) {
|
||||
func (bot TipBot) handle(endpoint interface{}, handler interface{}) {
|
||||
// register the endpoint
|
||||
bot.Telegram.Handle(endpoint, handler)
|
||||
switch endpoint.(type) {
|
||||
@@ -71,23 +90,24 @@ func (bot TipBot) handle(endpoint interface{}, handler tb.HandlerFunc) {
|
||||
}
|
||||
|
||||
// register registers a handler, so that Telegram can handle the endpoint correctly.
|
||||
func (bot TipBot) register(h InterceptionWrapper) {
|
||||
func (bot TipBot) register(h Handler) {
|
||||
if h.Interceptor != nil {
|
||||
bot.registerHandlerWithInterceptor(h)
|
||||
} else {
|
||||
for _, endpoint := range h.Endpoints {
|
||||
bot.handle(endpoint, intercept.WithHandler(h.Handler))
|
||||
bot.handle(endpoint, h.Handler)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// getHandler returns a list of all handlers, that need to be registered with Telegram
|
||||
func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
return []InterceptionWrapper{
|
||||
func (bot TipBot) getHandler() []Handler {
|
||||
return []Handler{
|
||||
{
|
||||
Endpoints: []interface{}{"/start"},
|
||||
Handler: bot.startHandler,
|
||||
Interceptor: &Interceptor{
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
@@ -100,9 +120,10 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/tip", "/t", "/honk"},
|
||||
Endpoints: []interface{}{"/tip"},
|
||||
Handler: bot.tipHandler,
|
||||
Interceptor: &Interceptor{
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
@@ -119,8 +140,8 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/pay"},
|
||||
Handler: bot.payHandler,
|
||||
Interceptor: &Interceptor{
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -135,9 +156,8 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/invoice", &btnInvoiceMainMenu},
|
||||
Handler: bot.invoiceHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -148,42 +168,11 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/node"},
|
||||
Handler: bot.nodeHandler,
|
||||
Interceptor: &Interceptor{
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{&btnSatdressCheckInvoice},
|
||||
Handler: bot.satdressCheckInvoiceHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/shops"},
|
||||
Handler: bot.shopsHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -198,7 +187,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/shop"},
|
||||
Handler: bot.shopHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
@@ -214,9 +203,8 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/balance", &btnBalanceMainMenu},
|
||||
Handler: bot.balanceHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -228,10 +216,10 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/send", &btnSendMenuEnter},
|
||||
Endpoints: []interface{}{"/send", &btnSendMainMenu},
|
||||
Handler: bot.sendHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
@@ -244,68 +232,11 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{&btnSendMainMenu},
|
||||
Handler: bot.keyboardSendHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.loadReplyToInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/transactions"},
|
||||
Handler: bot.transactionsHandler,
|
||||
Interceptor: &Interceptor{
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
}},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{&btnLeftTransactionsButton},
|
||||
Handler: bot.transactionsScrollLeftHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{&btnRightTransactionsButton},
|
||||
Handler: bot.transactionsScrollRightHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/faucet", "/zapfhahn", "/kraan", "/grifo"},
|
||||
Handler: bot.faucetHandler,
|
||||
Handler: bot.createFaucetHandler,
|
||||
Interceptor: &Interceptor{
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
@@ -321,7 +252,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/tipjar", "/spendendose"},
|
||||
Handler: bot.tipjarHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
@@ -337,7 +268,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/help", &btnHelpMainMenu},
|
||||
Handler: bot.helpHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
@@ -353,7 +284,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/basics"},
|
||||
Handler: bot.basicsHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
@@ -369,7 +300,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/donate"},
|
||||
Handler: bot.donationHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
@@ -385,7 +316,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/advanced"},
|
||||
Handler: bot.advancedHelpHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
@@ -401,7 +332,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/link"},
|
||||
Handler: bot.lndhubHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
@@ -417,7 +348,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{"/lnurl"},
|
||||
Handler: bot.lnurlHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
@@ -429,60 +360,11 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
},
|
||||
},
|
||||
},
|
||||
// group tickets
|
||||
{
|
||||
Endpoints: []interface{}{"/group"},
|
||||
Handler: bot.groupHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{"/join"},
|
||||
Handler: bot.groupRequestJoinHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.startUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{&btnPayTicket},
|
||||
Handler: bot.groupConfirmPayButtonHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{tb.OnPhoto},
|
||||
Handler: bot.photoHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
@@ -499,7 +381,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{tb.OnDocument, tb.OnVideo, tb.OnAnimation, tb.OnVoice, tb.OnAudio, tb.OnSticker, tb.OnVideoNote},
|
||||
Handler: bot.fileHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
@@ -509,7 +391,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{tb.OnText},
|
||||
Handler: bot.anyTextHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: MessageInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.requirePrivateChatInterceptor, // Respond to any text only in private chat
|
||||
bot.localizerInterceptor,
|
||||
@@ -526,6 +408,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{tb.OnQuery},
|
||||
Handler: bot.anyQueryHandler,
|
||||
Interceptor: &Interceptor{
|
||||
Type: QueryInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -537,14 +420,14 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{tb.OnInlineResult},
|
||||
Endpoints: []interface{}{tb.OnChosenInlineResult},
|
||||
Handler: bot.anyChosenInlineHandler,
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{&btnPay},
|
||||
Handler: bot.confirmPayHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -559,7 +442,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&btnCancelPay},
|
||||
Handler: bot.cancelPaymentHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -574,7 +457,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&btnSend},
|
||||
Handler: bot.confirmSendHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -589,7 +472,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&btnCancelSend},
|
||||
Handler: bot.cancelSendHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -604,7 +487,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&btnAcceptInlineSend},
|
||||
Handler: bot.acceptInlineSendHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -619,7 +502,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&btnCancelInlineSend},
|
||||
Handler: bot.cancelInlineSendHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -634,7 +517,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&btnAcceptInlineReceive},
|
||||
Handler: bot.acceptInlineReceiveHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -649,7 +532,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&btnCancelInlineReceive},
|
||||
Handler: bot.cancelInlineReceiveHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -662,9 +545,9 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{&btnAcceptInlineFaucet},
|
||||
Handler: bot.acceptInlineFaucetHandler,
|
||||
Handler: bot.acceptFaucetHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.singletonCallbackInterceptor,
|
||||
bot.localizerInterceptor,
|
||||
@@ -680,7 +563,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&btnCancelInlineFaucet},
|
||||
Handler: bot.cancelInlineFaucetHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -695,7 +578,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&btnAcceptInlineTipjar},
|
||||
Handler: bot.acceptInlineTipjarHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -710,7 +593,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&btnCancelInlineTipjar},
|
||||
Handler: bot.cancelInlineTipjarHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -725,7 +608,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&btnWithdraw},
|
||||
Handler: bot.confirmWithdrawHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -740,37 +623,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&btnCancelWithdraw},
|
||||
Handler: bot.cancelWithdrawHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{&btnAuth},
|
||||
Handler: bot.confirmLnurlAuthHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Endpoints: []interface{}{&btnCancelAuth},
|
||||
Handler: bot.cancelLnurlAuthHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
@@ -785,7 +638,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopNewShopButton},
|
||||
Handler: bot.shopNewShopHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -799,7 +652,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopAddItemButton},
|
||||
Handler: bot.shopNewItemHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -813,7 +666,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopBuyitemButton},
|
||||
Handler: bot.shopGetItemFilesHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -827,7 +680,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopNextitemButton},
|
||||
Handler: bot.shopNextItemButtonHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -841,7 +694,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&browseShopButton},
|
||||
Handler: bot.shopsBrowser,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -855,7 +708,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopSelectButton},
|
||||
Handler: bot.shopSelect,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -870,7 +723,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopDeleteShopButton},
|
||||
Handler: bot.shopsDeleteShopBrowser,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -885,7 +738,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopDeleteSelectButton},
|
||||
Handler: bot.shopSelectDelete,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -900,7 +753,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopLinkShopButton},
|
||||
Handler: bot.shopsLinkShopBrowser,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -915,7 +768,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopLinkSelectButton},
|
||||
Handler: bot.shopSelectLink,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -930,7 +783,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopRenameShopButton},
|
||||
Handler: bot.shopsRenameShopBrowser,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -945,7 +798,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopRenameSelectButton},
|
||||
Handler: bot.shopSelectRename,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -960,7 +813,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopSettingsButton},
|
||||
Handler: bot.shopSettingsHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -975,7 +828,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopDescriptionShopButton},
|
||||
Handler: bot.shopsDescriptionHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -990,7 +843,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopResetShopButton},
|
||||
Handler: bot.shopsResetHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -1004,7 +857,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopResetShopAskButton},
|
||||
Handler: bot.shopsAskDeleteAllShopsHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -1018,7 +871,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopPrevitemButton},
|
||||
Handler: bot.shopPrevItemButtonHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -1032,7 +885,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopShopsButton},
|
||||
Handler: bot.shopsHandlerCallback,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -1047,7 +900,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopItemSettingsButton},
|
||||
Handler: bot.shopItemSettingsHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -1061,7 +914,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopItemSettingsBackButton},
|
||||
Handler: bot.displayShopItemHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -1075,7 +928,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopItemDeleteButton},
|
||||
Handler: bot.shopItemDeleteHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -1089,7 +942,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopItemPriceButton},
|
||||
Handler: bot.shopItemPriceHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -1103,7 +956,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopItemTitleButton},
|
||||
Handler: bot.shopItemTitleHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -1117,7 +970,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopItemAddFileButton},
|
||||
Handler: bot.shopItemAddItemHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -1131,7 +984,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopItemBuyButton},
|
||||
Handler: bot.shopConfirmBuyHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
@@ -1145,7 +998,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
Endpoints: []interface{}{&shopItemCancelBuyButton},
|
||||
Handler: bot.displayShopItemHandler,
|
||||
Interceptor: &Interceptor{
|
||||
|
||||
Type: CallbackInterceptor,
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.loadUserInterceptor,
|
||||
|
||||
+22
-24
@@ -4,9 +4,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot TipBot) makeHelpMessage(ctx context.Context, m *tb.Message) string {
|
||||
@@ -28,26 +26,26 @@ func (bot TipBot) makeHelpMessage(ctx context.Context, m *tb.Message) string {
|
||||
return fmt.Sprintf(helpMessage, dynamicHelpMessage)
|
||||
}
|
||||
|
||||
func (bot TipBot) helpHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
func (bot TipBot) helpHandler(ctx context.Context, m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx)
|
||||
if !ctx.Message().Private() {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if !m.Private() {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(ctx.Message())
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
bot.trySendMessage(ctx.Sender(), bot.makeHelpMessage(ctx, ctx.Message()), tb.NoPreview)
|
||||
return ctx, nil
|
||||
bot.trySendMessage(m.Sender, bot.makeHelpMessage(ctx, m), tb.NoPreview)
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) basicsHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
func (bot TipBot) basicsHandler(ctx context.Context, m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx)
|
||||
if !ctx.Message().Private() {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if !m.Private() {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(ctx.Message())
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
bot.trySendMessage(ctx.Sender(), Translate(ctx, "basicsMessage"), tb.NoPreview)
|
||||
return ctx, nil
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "basicsMessage"), tb.NoPreview)
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) makeAdvancedHelpMessage(ctx context.Context, m *tb.Message) string {
|
||||
@@ -61,11 +59,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 := UserGetAnonLNURL(fromUser)
|
||||
lnurl, err := UserGetLNURL(fromUser)
|
||||
if err == nil {
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Anonymous LNURL: `%s`", lnurl)
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("LNURL: `%s`", lnurl)
|
||||
}
|
||||
|
||||
// this is so stupid:
|
||||
@@ -76,13 +74,13 @@ func (bot TipBot) makeAdvancedHelpMessage(ctx context.Context, m *tb.Message) st
|
||||
)
|
||||
}
|
||||
|
||||
func (bot TipBot) advancedHelpHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
func (bot TipBot) advancedHelpHandler(ctx context.Context, m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx)
|
||||
if !ctx.Message().Private() {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if !m.Private() {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(ctx.Message())
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
bot.trySendMessage(ctx.Sender(), bot.makeAdvancedHelpMessage(ctx, ctx.Message()), tb.NoPreview)
|
||||
return ctx, nil
|
||||
bot.trySendMessage(m.Sender, bot.makeAdvancedHelpMessage(ctx, m), tb.NoPreview)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -7,8 +7,6 @@ import (
|
||||
"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"
|
||||
@@ -20,28 +18,31 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
inlineFaucetMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
inlineFaucetMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelInlineFaucet = inlineFaucetMenu.Data("🚫 Cancel", "cancel_faucet_inline")
|
||||
btnAcceptInlineFaucet = inlineFaucetMenu.Data("✅ Collect", "confirm_faucet_inline")
|
||||
)
|
||||
|
||||
type InlineFaucet struct {
|
||||
const idTemplate = "faucet-%d-%d-%s"
|
||||
|
||||
type Faucet 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"`
|
||||
Message string `json:"faucet_message"`
|
||||
Amount int64 `json:"faucet_amount"`
|
||||
RemainingAmount int64 `json:"faucet_remainingamount"`
|
||||
PerUserAmount int64 `json:"faucet_peruseramount"`
|
||||
From *lnbits.User `json:"faucet_from"`
|
||||
To []*lnbits.User `json:"faucet_to"`
|
||||
Memo string `json:"faucet_memo"`
|
||||
NTotal int `json:"faucet_ntotal"`
|
||||
NTaken int `json:"faucet_ntaken"`
|
||||
UserNeedsWallet bool `json:"faucet_userneedswallet"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
}
|
||||
|
||||
@@ -53,7 +54,7 @@ func (bot TipBot) mapFaucetLanguage(ctx context.Context, command string) context
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User) (*InlineFaucet, error) {
|
||||
func (bot TipBot) createFaucet(ctx context.Context, text string, inline bool, sender *tb.User) (*Faucet, error) {
|
||||
amount, err := decodeAmountFromCommand(text)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.DecodeAmountError, err)
|
||||
@@ -83,13 +84,17 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
|
||||
// // 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))
|
||||
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("faucet:%s:%d", RandStringRunes(10), amount)
|
||||
|
||||
return &InlineFaucet{
|
||||
id := fmt.Sprintf(idTemplate, sender.ID, amount, RandStringRunes(5))
|
||||
if inline {
|
||||
id = fmt.Sprintf("inl-%s", id)
|
||||
}
|
||||
|
||||
return &Faucet{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Message: inlineMessage,
|
||||
Amount: amount,
|
||||
@@ -104,72 +109,70 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
|
||||
}, 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:
|
||||
func (bot TipBot) handleFaucetError(ctx context.Context, faucet interface{}, err error) {
|
||||
var m *tb.Message
|
||||
var q *tb.Query
|
||||
switch faucet.(type) {
|
||||
case *tb.Message:
|
||||
m = faucet.(*tb.Message)
|
||||
case *tb.Query:
|
||||
q = faucet.(*tb.Query)
|
||||
}
|
||||
switch err.(errors.TipBotError).Code {
|
||||
case errors.DecodeAmountError:
|
||||
if q != nil {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
} else if m != nil {
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.DecodePerUserAmountError:
|
||||
}
|
||||
|
||||
case errors.DecodePerUserAmountError:
|
||||
if q != nil {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
} else if m != nil {
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), ""))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.InvalidAmountError:
|
||||
}
|
||||
|
||||
case errors.InvalidAmountError:
|
||||
if q != nil {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
} else if m != nil {
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.InvalidAmountPerUserError:
|
||||
}
|
||||
|
||||
case errors.InvalidAmountPerUserError:
|
||||
if q != nil {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineFaucetInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
} else if m != nil {
|
||||
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())
|
||||
}
|
||||
case errors.GetBalanceError:
|
||||
if q != nil {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
} else if m != nil {
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.BalanceToLowError:
|
||||
// log.Errorf(err.Error())
|
||||
}
|
||||
case errors.BalanceToLowError:
|
||||
if q != nil {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
} else if m != nil {
|
||||
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 := &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,
|
||||
@@ -178,34 +181,30 @@ func (bot TipBot) makeFaucetKeyboard(ctx context.Context, id string) *tb.ReplyMa
|
||||
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)
|
||||
func (bot TipBot) createFaucetHandler(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.Context = bot.mapFaucetLanguage(ctx, ctx.Text())
|
||||
inlineFaucet, err := bot.makeFaucet(ctx, ctx.Message(), false)
|
||||
ctx = bot.mapFaucetLanguage(ctx, m.Text)
|
||||
inlineFaucet, err := bot.createFaucet(ctx, m.Text, false, m.Sender)
|
||||
if err != nil {
|
||||
log.Warnf("[faucet] %s", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
fromUserStr := GetUserStr(ctx.Message().Sender)
|
||||
mFaucet := bot.trySendMessage(ctx.Message().Chat, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
|
||||
fromUserStr := GetUserStr(m.Sender)
|
||||
bot.trySendMessage(m.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)
|
||||
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineFaucetQuery(ctx intercept.Context) (intercept.Context, error) {
|
||||
inlineFaucet, err := bot.makeQueryFaucet(ctx)
|
||||
func (bot TipBot) createInlineFaucetHandler(ctx context.Context, q *tb.Query) {
|
||||
inlineFaucet, err := bot.createFaucet(ctx, q.Text, true, &q.From)
|
||||
if err != nil {
|
||||
log.Errorf("[handleInlineFaucetQuery] %s", err.Error())
|
||||
return ctx, err
|
||||
bot.handleFaucetError(ctx, q, err)
|
||||
log.Errorf("[createInlineFaucetHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
urls := []string{
|
||||
queryImage,
|
||||
@@ -220,7 +219,7 @@ func (bot TipBot) handleInlineFaucetQuery(ctx intercept.Context) (intercept.Cont
|
||||
// required for photos
|
||||
ThumbURL: url,
|
||||
}
|
||||
result.ReplyMarkup = &tb.ReplyMarkup{InlineKeyboard: bot.makeFaucetKeyboard(ctx, inlineFaucet.ID).InlineKeyboard}
|
||||
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)
|
||||
@@ -229,55 +228,49 @@ func (bot TipBot) handleInlineFaucetQuery(ctx intercept.Context) (intercept.Cont
|
||||
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{
|
||||
err = bot.Telegram.Answer(q, &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()
|
||||
func (bot *TipBot) acceptFaucetHandler(ctx context.Context, c *tb.Callback) {
|
||||
to := LoadUser(ctx)
|
||||
tx := &InlineFaucet{Base: storage.New(storage.ID(c.Data))}
|
||||
tx := &Faucet{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.Debugf("[acceptFaucetHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
log.Tracef("[acceptInlineFaucetHandler] Callback c.Data: %s tx.ID: %s", c.Data, tx.ID)
|
||||
|
||||
inlineFaucet := fn.(*InlineFaucet)
|
||||
inlineFaucet := fn.(*Faucet)
|
||||
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)
|
||||
log.Debugf("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(c.Message.Chat.ID, 10)[4:], c.Message.ID)
|
||||
}
|
||||
if !inlineFaucet.Active {
|
||||
log.Debugf(fmt.Sprintf("[faucet] faucet %s inactive. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
|
||||
bot.finishFaucet(ctx, c, inlineFaucet)
|
||||
return
|
||||
}
|
||||
// release faucet no matter what
|
||||
|
||||
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)
|
||||
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.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)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,7 +288,7 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx intercept.Context) (intercept.C
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[faucet] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -304,22 +297,20 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx intercept.Context) (intercept.C
|
||||
}
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("🚰 Faucet from %s to %s.", fromUserStr, toUserStr)
|
||||
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"))
|
||||
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)
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[💸 faucet] Faucet %s from %s to %s:%d (%d sat).", inlineFaucet.ID, fromUserStr, toUserStr, to.Telegram.ID, inlineFaucet.PerUserAmount)
|
||||
@@ -327,95 +318,75 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx intercept.Context) (intercept.C
|
||||
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))
|
||||
_, 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.Error())
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
}()
|
||||
|
||||
// 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))
|
||||
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"), GetUserStr(bot.Telegram.Me))
|
||||
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(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))
|
||||
go func() {
|
||||
bot.tryEditMessage(c.Message, 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))}
|
||||
func (bot *TipBot) cancelInlineFaucet(ctx context.Context, c *tb.Callback, ignoreID bool) {
|
||||
tx := &Faucet{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
|
||||
return
|
||||
}
|
||||
|
||||
inlineFaucet := fn.(*InlineFaucet)
|
||||
inlineFaucet := fn.(*Faucet)
|
||||
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)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineFaucet inactive
|
||||
inlineFaucet.Active = false
|
||||
inlineFaucet.Canceled = true
|
||||
err = inlineFaucet.Set(inlineFaucet, bot.Bunt)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
|
||||
log.Debugf("[faucet] Faucet %s canceled.", inlineFaucet.ID)
|
||||
once.Remove(inlineFaucet.ID)
|
||||
}
|
||||
return ctx, nil
|
||||
return
|
||||
}
|
||||
|
||||
func (bot *TipBot) finishFaucet(ctx context.Context, c *tb.Callback, inlineFaucet *InlineFaucet) {
|
||||
func (bot *TipBot) finishFaucet(ctx context.Context, c *tb.Callback, inlineFaucet *Faucet) {
|
||||
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{})
|
||||
|
||||
bot.tryEditMessage(c.Message, inlineFaucet.Message, &tb.ReplyMarkup{})
|
||||
inlineFaucet.Active = false
|
||||
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
|
||||
|
||||
func (bot *TipBot) cancelInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
|
||||
bot.cancelInlineFaucet(ctx, c, false)
|
||||
return
|
||||
}
|
||||
@@ -7,20 +7,18 @@ import (
|
||||
"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/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
const queryImage = "https://avatars.githubusercontent.com/u/88730856?v=7"
|
||||
const queryImage = "https://avatars.githubusercontent.com/u/88730856?v=4"
|
||||
|
||||
func (bot TipBot) inlineQueryInstructions(ctx intercept.Context) (intercept.Context, error) {
|
||||
func (bot TipBot) inlineQueryInstructions(ctx context.Context, q *tb.Query) {
|
||||
instructions := []struct {
|
||||
url string
|
||||
title string
|
||||
@@ -62,20 +60,19 @@ func (bot TipBot) inlineQueryInstructions(ctx intercept.Context) (intercept.Cont
|
||||
results[i].SetResultID(strconv.Itoa(i))
|
||||
}
|
||||
|
||||
err := ctx.Answer(&tb.QueryResponse{
|
||||
err := bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
Results: results,
|
||||
CacheTime: 5, // a minute
|
||||
IsPersonal: true,
|
||||
QueryID: ctx.Query().ID,
|
||||
QueryID: q.ID,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
func (bot TipBot) inlineQueryReplyWithError(ctx intercept.Context, message string, help string) {
|
||||
func (bot TipBot) inlineQueryReplyWithError(q *tb.Query, message string, help string) {
|
||||
results := make(tb.Results, 1) // []tb.Result
|
||||
result := &tb.ArticleResult{
|
||||
// URL: url,
|
||||
@@ -85,12 +82,11 @@ func (bot TipBot) inlineQueryReplyWithError(ctx intercept.Context, message strin
|
||||
// required for photos
|
||||
ThumbURL: queryImage,
|
||||
}
|
||||
id := fmt.Sprintf("inl-error-%d-%s", ctx.Query().Sender.ID, RandStringRunes(5))
|
||||
id := fmt.Sprintf("inl-error-%d-%s", q.From.ID, RandStringRunes(5))
|
||||
result.SetResultID(id)
|
||||
results[0] = result
|
||||
err := ctx.Answer(&tb.QueryResponse{
|
||||
Results: results,
|
||||
|
||||
err := bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
Results: results,
|
||||
CacheTime: 1, // 60 == 1 minute, todo: make higher than 1 s in production
|
||||
|
||||
})
|
||||
@@ -101,22 +97,21 @@ func (bot TipBot) inlineQueryReplyWithError(ctx intercept.Context, message strin
|
||||
|
||||
// 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) {
|
||||
func (bot TipBot) anyChosenInlineHandler(q *tb.ChosenInlineResult) {
|
||||
// load inline object from cache
|
||||
inlineObject, err := bot.Cache.Get(ctx.InlineResult().ResultID)
|
||||
inlineObject, err := bot.Cache.Get(q.ResultID)
|
||||
// check error
|
||||
if err != nil {
|
||||
log.Errorf("[anyChosenInlineHandler] could not find inline object in cache. %v", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
switch inlineObject.(type) {
|
||||
case storage.Storable:
|
||||
// persist inline object in bunt
|
||||
runtime.IgnoreError(bot.Bunt.Set(inlineObject.(storage.Storable)))
|
||||
default:
|
||||
log.Errorf("[anyChosenInlineHandler] invalid inline object type: %s, query: %s", reflect.TypeOf(inlineObject).String(), ctx.InlineResult().Query)
|
||||
log.Errorf("[anyChosenInlineHandler] invalid inline object type: %s, query: %s", reflect.TypeOf(inlineObject).String(), q.Query)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot TipBot) commandTranslationMap(ctx context.Context, command string) context.Context {
|
||||
@@ -138,37 +133,36 @@ func (bot TipBot) commandTranslationMap(ctx context.Context, command string) con
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (bot TipBot) anyQueryHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
if ctx.Query().Text == "" {
|
||||
return bot.inlineQueryInstructions(ctx)
|
||||
func (bot TipBot) anyQueryHandler(ctx context.Context, q *tb.Query) {
|
||||
if q.Text == "" {
|
||||
bot.inlineQueryInstructions(ctx, q)
|
||||
return
|
||||
}
|
||||
|
||||
// create the inline send result
|
||||
var text = ctx.Query().Text
|
||||
if strings.HasPrefix(text, "/") {
|
||||
text = strings.TrimPrefix(text, "/")
|
||||
if strings.HasPrefix(q.Text, "/") {
|
||||
q.Text = strings.TrimPrefix(q.Text, "/")
|
||||
}
|
||||
if strings.HasPrefix(text, "send") || strings.HasPrefix(text, "pay") {
|
||||
return bot.handleInlineSendQuery(ctx)
|
||||
if strings.HasPrefix(q.Text, "send") || strings.HasPrefix(q.Text, "pay") {
|
||||
bot.handleInlineSendQuery(ctx, q)
|
||||
}
|
||||
|
||||
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)
|
||||
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)
|
||||
}
|
||||
return bot.handleInlineFaucetQuery(ctx)
|
||||
bot.createInlineFaucetHandler(ctx, q)
|
||||
}
|
||||
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)
|
||||
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)
|
||||
}
|
||||
return bot.handleInlineTipjarQuery(ctx)
|
||||
bot.handleInlineTipjarQuery(ctx, q)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(text, "receive") || strings.HasPrefix(text, "get") || strings.HasPrefix(text, "payme") || strings.HasPrefix(text, "request") {
|
||||
return bot.handleInlineReceiveQuery(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)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -7,9 +7,6 @@ import (
|
||||
"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"
|
||||
|
||||
@@ -21,11 +18,11 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
inlineReceiveMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
inlineReceiveMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelInlineReceive = inlineReceiveMenu.Data("🚫 Cancel", "cancel_receive_inline")
|
||||
btnAcceptInlineReceive = inlineReceiveMenu.Data("💸 Pay", "confirm_receive_inline")
|
||||
)
|
||||
@@ -33,7 +30,7 @@ var (
|
||||
type InlineReceive struct {
|
||||
*storage.Base
|
||||
MessageText string `json:"inline_receive_messagetext"`
|
||||
Message tb.Editable `json:"inline_receive_message"`
|
||||
Message *tb.Message `json:"inline_receive_message"`
|
||||
Amount int64 `json:"inline_receive_amount"`
|
||||
From *lnbits.User `json:"inline_receive_from"`
|
||||
To *lnbits.User `json:"inline_receive_to"`
|
||||
@@ -43,7 +40,6 @@ 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
|
||||
@@ -57,19 +53,18 @@ func (bot TipBot) makeReceiveKeyboard(ctx context.Context, id string) *tb.ReplyM
|
||||
return inlineReceiveMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineReceiveQuery(ctx intercept.Context) (intercept.Context, error) {
|
||||
q := ctx.Query()
|
||||
func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
|
||||
to := LoadUser(ctx)
|
||||
amount, err := decodeAmountFromCommand(q.Text)
|
||||
if err != nil {
|
||||
bot.inlineQueryReplyWithError(ctx, Translate(ctx, "inlineQueryReceiveTitle"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, err
|
||||
bot.inlineQueryReplyWithError(q, Translate(ctx, "inlineQueryReceiveTitle"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
|
||||
return
|
||||
}
|
||||
if amount < 1 {
|
||||
bot.inlineQueryReplyWithError(ctx, Translate(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
bot.inlineQueryReplyWithError(q, Translate(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
|
||||
return
|
||||
}
|
||||
toUserStr := GetUserStr(q.Sender)
|
||||
toUserStr := GetUserStr(&q.From)
|
||||
|
||||
// check whether the 3rd argument is a username
|
||||
// command is "@LightningTipBot receive 123 @from_user This is the memo"
|
||||
@@ -83,11 +78,11 @@ func (bot TipBot) handleInlineReceiveQuery(ctx intercept.Context) (intercept.Con
|
||||
if err != nil {
|
||||
//bot.tryDeleteMessage(m)
|
||||
//bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), toUserStrMention))
|
||||
bot.inlineQueryReplyWithError(ctx,
|
||||
bot.inlineQueryReplyWithError(q,
|
||||
fmt.Sprintf(TranslateUser(ctx, "sendUserHasNoWalletMessage"), from_username),
|
||||
fmt.Sprintf(TranslateUser(ctx, "inlineQueryReceiveDescription"),
|
||||
bot.Telegram.Me.Username))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
memo_argn = 3 // assume that memo starts after the from_username
|
||||
from_SpecificUser = true
|
||||
@@ -119,8 +114,8 @@ func (bot TipBot) handleInlineReceiveQuery(ctx intercept.Context) (intercept.Con
|
||||
// required for photos
|
||||
ThumbURL: url,
|
||||
}
|
||||
id := fmt.Sprintf("inl-receive-%d-%d-%s", q.Sender.ID, amount, RandStringRunes(5))
|
||||
result.ReplyMarkup = &tb.ReplyMarkup{InlineKeyboard: bot.makeReceiveKeyboard(ctx, id).InlineKeyboard}
|
||||
id := fmt.Sprintf("inl-receive-%d-%d-%s", q.From.ID, amount, RandStringRunes(5))
|
||||
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeReceiveKeyboard(ctx, id).InlineKeyboard}
|
||||
results[i] = result
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(id)
|
||||
@@ -145,13 +140,10 @@ func (bot TipBot) handleInlineReceiveQuery(ctx intercept.Context) (intercept.Con
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
@@ -159,12 +151,12 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx intercept.Context) (intercept.
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[getInlineReceive] %s", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
if !inlineReceive.Active {
|
||||
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
return
|
||||
}
|
||||
|
||||
// user `from` is the one who is SENDING
|
||||
@@ -174,20 +166,20 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx intercept.Context) (intercept.
|
||||
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 ctx, errors.Create(errors.UnknownError)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// otherwise, we just set it to the user who has clicked
|
||||
inlineReceive.From = from
|
||||
|
||||
}
|
||||
inlineReceive.Message = c
|
||||
inlineReceive.Message = c.Message
|
||||
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
|
||||
|
||||
to := inlineReceive.To
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return ctx, errors.Create(errors.SelfPaymentError)
|
||||
return
|
||||
}
|
||||
|
||||
balance, err := bot.GetUserBalance(from)
|
||||
@@ -200,16 +192,16 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx intercept.Context) (intercept.
|
||||
// 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)
|
||||
bot.inlineReceiveInvoice(ctx, c, inlineReceive)
|
||||
return
|
||||
} else {
|
||||
// else, do an internal transaction
|
||||
return bot.sendInlineReceiveHandler(ctx)
|
||||
bot.sendInlineReceiveHandler(ctx, c)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) sendInlineReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
func (bot *TipBot) sendInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
@@ -217,13 +209,13 @@ func (bot *TipBot) sendInlineReceiveHandler(ctx intercept.Context) (intercept.Co
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
// log.Errorf("[getInlineReceive] %s", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
|
||||
if !inlineReceive.Active {
|
||||
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
return
|
||||
}
|
||||
|
||||
// defer inlineReceive.Release(inlineReceive, bot.Bunt)
|
||||
@@ -238,38 +230,36 @@ func (bot *TipBot) sendInlineReceiveHandler(ctx intercept.Context) (intercept.Co
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
// 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 ctx, errors.Create(errors.BalanceToLowError)
|
||||
return
|
||||
}
|
||||
|
||||
// set inactive to avoid double-sends
|
||||
inlineReceive.Inactivate(inlineReceive, bot.Bunt)
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("💸 Receive from %s to %s.", fromUserStr, toUserStr)
|
||||
transactionMemo := fmt.Sprintf("InlineReceive from %s to %s (%d sat).", fromUserStr, toUserStr, inlineReceive.Amount)
|
||||
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.Error())
|
||||
log.Errorln(errMsg)
|
||||
bot.tryEditMessage(c, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveFailedMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveFailedMessage"), &tb.ReplyMarkup{})
|
||||
return
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
bot.finishInlineReceiveHandler(ctx, c)
|
||||
}
|
||||
|
||||
func (bot *TipBot) inlineReceiveInvoice(ctx intercept.Context, inlineReceive *InlineReceive) {
|
||||
func (bot *TipBot) inlineReceiveInvoice(ctx context.Context, c *tb.Callback, inlineReceive *InlineReceive) {
|
||||
if !inlineReceive.Active {
|
||||
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
|
||||
return
|
||||
@@ -292,31 +282,33 @@ func (bot *TipBot) inlineReceiveInvoice(ctx intercept.Context, inlineReceive *In
|
||||
}
|
||||
|
||||
// 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))
|
||||
var msg *tb.Message
|
||||
if inlineReceive.Message.Chat != nil {
|
||||
msg = bot.trySendMessage(inlineReceive.Message.Chat, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
} else {
|
||||
msg = bot.trySendMessage(c.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)
|
||||
func (bot *TipBot) inlineReceiveEvent(invoiceEvent *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) {
|
||||
func (bot *TipBot) finishInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
|
||||
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)
|
||||
}
|
||||
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
|
||||
return
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
|
||||
@@ -325,7 +317,7 @@ func (bot *TipBot) finishInlineReceiveHandler(ctx context.Context, c *tb.Callbac
|
||||
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)
|
||||
inlineReceive.MessageText = fmt.Sprintf("%s", 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)
|
||||
@@ -337,19 +329,16 @@ func (bot *TipBot) finishInlineReceiveHandler(ctx context.Context, c *tb.Callbac
|
||||
|
||||
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))
|
||||
_, 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))
|
||||
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()
|
||||
func (bot *TipBot) cancelInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
@@ -357,14 +346,14 @@ func (bot *TipBot) cancelInlineReceiveHandler(ctx intercept.Context) (intercept.
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineReceiveHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
if c.Sender.ID != inlineReceive.To.Telegram.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
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
|
||||
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
|
||||
}
|
||||
bot.tryEditMessage(c, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineReceive inactive
|
||||
inlineReceive.Active = false
|
||||
return ctx, inlineReceive.Set(inlineReceive, bot.Bunt)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -6,9 +6,6 @@ import (
|
||||
"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"
|
||||
|
||||
@@ -18,12 +15,13 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
inlineSendMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
inlineSendMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelInlineSend = inlineSendMenu.Data("🚫 Cancel", "cancel_send_inline")
|
||||
btnAcceptInlineSend = inlineSendMenu.Data("✅ Receive", "confirm_send_inline")
|
||||
)
|
||||
@@ -40,7 +38,6 @@ 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
|
||||
@@ -54,32 +51,31 @@ func (bot TipBot) makeSendKeyboard(ctx context.Context, id string) *tb.ReplyMark
|
||||
return inlineSendMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineSendQuery(ctx intercept.Context) (intercept.Context, error) {
|
||||
q := ctx.Query()
|
||||
func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
|
||||
// inlineSend := NewInlineSend()
|
||||
// var err error
|
||||
amount, err := decodeAmountFromCommand(q.Text)
|
||||
if err != nil {
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQuerySendTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, err
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQuerySendTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return
|
||||
}
|
||||
if amount < 1 {
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return
|
||||
}
|
||||
fromUser := LoadUser(ctx)
|
||||
fromUserStr := GetUserStr(q.Sender)
|
||||
fromUserStr := GetUserStr(&q.From)
|
||||
balance, err := bot.GetUserBalanceCached(fromUser)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
// check if fromUser has balance
|
||||
if balance < amount {
|
||||
log.Errorf("Balance of user %s too low", fromUserStr)
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return
|
||||
}
|
||||
|
||||
// check whether the 3rd argument is a username
|
||||
@@ -94,11 +90,11 @@ func (bot TipBot) handleInlineSendQuery(ctx intercept.Context) (intercept.Contex
|
||||
if err != nil {
|
||||
//bot.tryDeleteMessage(m)
|
||||
//bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), toUserStrMention))
|
||||
bot.inlineQueryReplyWithError(ctx,
|
||||
bot.inlineQueryReplyWithError(q,
|
||||
fmt.Sprintf(TranslateUser(ctx, "sendUserHasNoWalletMessage"), to_username),
|
||||
fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"),
|
||||
bot.Telegram.Me.Username))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
memo_argn = 3 // assume that memo starts after the to_username
|
||||
to_SpecificUser = true
|
||||
@@ -130,8 +126,8 @@ func (bot TipBot) handleInlineSendQuery(ctx intercept.Context) (intercept.Contex
|
||||
// required for photos
|
||||
ThumbURL: url,
|
||||
}
|
||||
id := fmt.Sprintf("inl-send-%d-%d-%s", q.Sender.ID, amount, RandStringRunes(5))
|
||||
result.ReplyMarkup = &tb.ReplyMarkup{InlineKeyboard: bot.makeSendKeyboard(ctx, id).InlineKeyboard}
|
||||
id := fmt.Sprintf("inl-send-%d-%d-%s", q.From.ID, amount, RandStringRunes(5))
|
||||
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeSendKeyboard(ctx, id).InlineKeyboard}
|
||||
results[i] = result
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(id)
|
||||
@@ -159,13 +155,10 @@ func (bot TipBot) handleInlineSendQuery(ctx intercept.Context) (intercept.Contex
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineSendHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
to := LoadUser(ctx)
|
||||
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
@@ -174,14 +167,14 @@ func (bot *TipBot) acceptInlineSendHandler(ctx intercept.Context) (intercept.Con
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
// log.Errorf("[acceptInlineSendHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
inlineSend := sn.(*InlineSend)
|
||||
|
||||
fromUser := inlineSend.From
|
||||
if !inlineSend.Active {
|
||||
log.Errorf("[acceptInlineSendHandler] inline send not active anymore")
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
return
|
||||
}
|
||||
|
||||
defer inlineSend.Set(inlineSend, bot.Bunt)
|
||||
@@ -192,7 +185,7 @@ func (bot *TipBot) acceptInlineSendHandler(ctx intercept.Context) (intercept.Con
|
||||
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 ctx, errors.Create(errors.UnknownError)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// otherwise, we just set it to the user who has clicked
|
||||
@@ -201,7 +194,7 @@ func (bot *TipBot) acceptInlineSendHandler(ctx intercept.Context) (intercept.Con
|
||||
|
||||
if fromUser.Telegram.ID == to.Telegram.ID {
|
||||
bot.trySendMessage(fromUser.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
return
|
||||
}
|
||||
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
@@ -217,22 +210,22 @@ func (bot *TipBot) acceptInlineSendHandler(ctx intercept.Context) (intercept.Con
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[sendInline] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
}
|
||||
// set inactive to avoid double-sends
|
||||
inlineSend.Inactivate(inlineSend, bot.Bunt)
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("💸 Send from %s to %s.", fromUserStr, toUserStr)
|
||||
transactionMemo := fmt.Sprintf("InlineSend from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
t := NewTransaction(bot, fromUser, to, amount, TransactionType("inline send"))
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
errMsg := fmt.Sprintf("[sendInline] Transaction failed: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
bot.tryEditMessage(c, i18n.Translate(inlineSend.LanguageCode, "inlineSendFailedMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "inlineSendFailedMessage"), &tb.ReplyMarkup{})
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[💸 sendInline] Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
@@ -245,19 +238,17 @@ func (bot *TipBot) acceptInlineSendHandler(ctx intercept.Context) (intercept.Con
|
||||
if !to.Initialized {
|
||||
inlineSend.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineSend.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
bot.tryEditMessage(c, inlineSend.Message, &tb.ReplyMarkup{})
|
||||
bot.tryEditMessage(c.Message, inlineSend.Message, &tb.ReplyMarkup{})
|
||||
// notify users
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
|
||||
bot.trySendMessage(fromUser.Telegram, fmt.Sprintf(i18n.Translate(fromUser.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
|
||||
_, 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))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[sendInline] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineSendHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
func (bot *TipBot) cancelInlineSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
@@ -265,14 +256,14 @@ func (bot *TipBot) cancelInlineSendHandler(ctx intercept.Context) (intercept.Con
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineSendHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
inlineSend := sn.(*InlineSend)
|
||||
if c.Sender.ID != inlineSend.From.Telegram.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
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
|
||||
runtime.IgnoreError(inlineSend.Set(inlineSend, bot.Bunt))
|
||||
}
|
||||
bot.tryEditMessage(c, i18n.Translate(inlineSend.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineSend inactive
|
||||
inlineSend.Active = false
|
||||
return ctx, inlineSend.Set(inlineSend, bot.Bunt)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -6,8 +6,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
@@ -17,12 +15,13 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
inlineTipjarMenu = &tb.ReplyMarkup{ResizeKeyboard: false}
|
||||
inlineTipjarMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: false}
|
||||
btnCancelInlineTipjar = inlineTipjarMenu.Data("🚫", "cancel_tipjar_inline")
|
||||
btnAcceptInlineTipjar = inlineTipjarMenu.Data("💸 Pay", "confirm_tipjar_inline")
|
||||
)
|
||||
@@ -83,7 +82,7 @@ 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("tipjar:%s:%d", RandStringRunes(10), amount)
|
||||
id := fmt.Sprintf("inl-tipjar-%d-%d-%s", sender.ID, amount, RandStringRunes(5))
|
||||
|
||||
return &InlineTipjar{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
@@ -133,28 +132,28 @@ func (bot TipBot) makeTipjar(ctx context.Context, m *tb.Message, query bool) (*I
|
||||
return tipjar, err
|
||||
}
|
||||
|
||||
func (bot TipBot) makeQueryTipjar(ctx intercept.Context) (*InlineTipjar, error) {
|
||||
tipjar, err := bot.createTipjar(ctx, ctx.Query().Text, ctx.Query().Sender)
|
||||
func (bot TipBot) makeQueryTipjar(ctx context.Context, q *tb.Query, query bool) (*InlineTipjar, error) {
|
||||
tipjar, err := bot.createTipjar(ctx, q.Text, &q.From)
|
||||
if err != nil {
|
||||
switch err.(errors.TipBotError).Code {
|
||||
case errors.DecodeAmountError:
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.DecodePerUserAmountError:
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.InvalidAmountError:
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.InvalidAmountPerUserError:
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineTipjarInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineTipjarInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.GetBalanceError:
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.BalanceToLowError:
|
||||
log.Errorf(err.Error())
|
||||
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -162,7 +161,7 @@ func (bot TipBot) makeQueryTipjar(ctx intercept.Context) (*InlineTipjar, error)
|
||||
}
|
||||
|
||||
func (bot TipBot) makeTipjarKeyboard(ctx context.Context, inlineTipjar *InlineTipjar) *tb.ReplyMarkup {
|
||||
inlineTipjarMenu := &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
// inlineTipjarMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
// slice of buttons
|
||||
buttons := make([]tb.Btn, 0)
|
||||
cancelInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_tipjar_inline", inlineTipjar.ID)
|
||||
@@ -175,31 +174,29 @@ func (bot TipBot) makeTipjarKeyboard(ctx context.Context, inlineTipjar *InlineTi
|
||||
return inlineTipjarMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) tipjarHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
bot.anyTextHandler(ctx)
|
||||
func (bot TipBot) tipjarHandler(ctx context.Context, m *tb.Message) {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if m.Private() {
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineTipjarHelpText"), Translate(ctx, "inlineTipjarHelpTipjarInGroup")))
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
return
|
||||
}
|
||||
ctx.Context = bot.mapTipjarLanguage(ctx, m.Text)
|
||||
ctx = bot.mapTipjarLanguage(ctx, m.Text)
|
||||
inlineTipjar, err := bot.makeTipjar(ctx, m, false)
|
||||
if err != nil {
|
||||
log.Errorf("[tipjar] %s", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
toUserStr := GetUserStr(m.Sender)
|
||||
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)
|
||||
return ctx, inlineTipjar.Set(inlineTipjar, bot.Bunt)
|
||||
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineTipjarQuery(ctx intercept.Context) (intercept.Context, error) {
|
||||
q := ctx.Query()
|
||||
inlineTipjar, err := bot.makeQueryTipjar(ctx)
|
||||
func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) {
|
||||
inlineTipjar, err := bot.makeQueryTipjar(ctx, q, false)
|
||||
if err != nil {
|
||||
// log.Errorf("[tipjar] %s", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
urls := []string{
|
||||
queryImage,
|
||||
@@ -214,7 +211,7 @@ func (bot TipBot) handleInlineTipjarQuery(ctx intercept.Context) (intercept.Cont
|
||||
// required for photos
|
||||
ThumbURL: url,
|
||||
}
|
||||
result.ReplyMarkup = &tb.ReplyMarkup{InlineKeyboard: bot.makeTipjarKeyboard(ctx, inlineTipjar).InlineKeyboard}
|
||||
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeTipjarKeyboard(ctx, inlineTipjar).InlineKeyboard}
|
||||
results[i] = result
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(inlineTipjar.ID)
|
||||
@@ -230,16 +227,13 @@ func (bot TipBot) handleInlineTipjarQuery(ctx intercept.Context) (intercept.Cont
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineTipjarHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback) {
|
||||
from := LoadUser(ctx)
|
||||
if from.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
tx := &InlineTipjar{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
@@ -247,31 +241,27 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx intercept.Context) (intercept.C
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
// log.Errorf("[tipjar] %s", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
inlineTipjar := fn.(*InlineTipjar)
|
||||
to := inlineTipjar.To
|
||||
if !inlineTipjar.Active {
|
||||
log.Errorf(fmt.Sprintf("[tipjar] tipjar %s inactive.", inlineTipjar.ID))
|
||||
bot.tryEditMessage(c, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
return
|
||||
}
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return ctx, errors.Create(errors.SelfPaymentError)
|
||||
return
|
||||
}
|
||||
// // check if to user has already given to the tipjar
|
||||
for _, a := range inlineTipjar.From {
|
||||
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 ctx, errors.Create(errors.UnknownError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
defer inlineTipjar.Set(inlineTipjar, bot.Bunt)
|
||||
|
||||
if inlineTipjar.GivenAmount < inlineTipjar.Amount {
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
@@ -279,7 +269,7 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx intercept.Context) (intercept.C
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("🍯 Tipjar from %s to %s.", fromUserStr, toUserStr)
|
||||
transactionMemo := fmt.Sprintf("Tipjar from %s to %s (%d sat).", fromUserStr, toUserStr, inlineTipjar.PerUserAmount)
|
||||
t := NewTransaction(bot, from, to, inlineTipjar.PerUserAmount, TransactionType("tipjar"))
|
||||
t.Memo = transactionMemo
|
||||
|
||||
@@ -288,7 +278,7 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx intercept.Context) (intercept.C
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
|
||||
errMsg := fmt.Sprintf("[tipjar] Transaction failed: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
return ctx, errors.New(errors.UnknownError, err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[💸 tipjar] Tipjar %s from %s to %s (%d sat).", inlineTipjar.ID, fromUserStr, toUserStr, inlineTipjar.PerUserAmount)
|
||||
@@ -296,8 +286,8 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx intercept.Context) (intercept.C
|
||||
inlineTipjar.From = append(inlineTipjar.From, from)
|
||||
inlineTipjar.GivenAmount = inlineTipjar.GivenAmount + inlineTipjar.PerUserAmount
|
||||
|
||||
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))
|
||||
_, 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))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[tipjar] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Warnln(errmsg)
|
||||
@@ -317,9 +307,12 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx intercept.Context) (intercept.C
|
||||
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, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
|
||||
bot.tryEditMessage(c.Message, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
|
||||
}
|
||||
if inlineTipjar.GivenAmount >= inlineTipjar.Amount {
|
||||
// tipjar is full
|
||||
@@ -329,50 +322,30 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx intercept.Context) (intercept.C
|
||||
inlineTipjar.Amount,
|
||||
inlineTipjar.NGiven,
|
||||
)
|
||||
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))
|
||||
}
|
||||
// if inlineTipjar.UserNeedsWallet {
|
||||
// inlineTipjar.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
// }
|
||||
bot.tryEditMessage(c.Message, inlineTipjar.Message)
|
||||
inlineTipjar.Active = false
|
||||
}
|
||||
return ctx, nil
|
||||
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineTipjarHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
func (bot *TipBot) cancelInlineTipjarHandler(ctx context.Context, c *tb.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("[cancelInlineTipjarHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
inlineTipjar := fn.(*InlineTipjar)
|
||||
if c.Sender.ID != inlineTipjar.To.Telegram.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
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
|
||||
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
|
||||
}
|
||||
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
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/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
|
||||
onDefer 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 WithDeferCallback(chain ...Func) CallbackInterceptOption {
|
||||
return func(a *handlerCallbackInterceptor) {
|
||||
a.onDefer = 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 := context.Background()
|
||||
ctx, err := interceptCallback(ctx, c, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
defer interceptCallback(ctx, c, hm.onDefer)
|
||||
hm.handler(ctx, c)
|
||||
_, err = interceptCallback(ctx, c, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/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
|
||||
onDefer 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 WithDeferMessage(chain ...Func) MessageInterceptOption {
|
||||
return func(a *handlerMessageInterceptor) {
|
||||
a.onDefer = 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 := context.Background()
|
||||
ctx, err := interceptMessage(ctx, message, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
defer interceptMessage(ctx, message, hm.onDefer)
|
||||
hm.handler(ctx, message)
|
||||
_, err = interceptMessage(ctx, message, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type QueryFuncHandler func(ctx context.Context, message *tb.Query)
|
||||
|
||||
type handlerQueryInterceptor struct {
|
||||
handler QueryFuncHandler
|
||||
before QueryChain
|
||||
after QueryChain
|
||||
onDefer 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 WithDeferQuery(chain ...Func) QueryInterceptOption {
|
||||
return func(a *handlerQueryInterceptor) {
|
||||
a.onDefer = 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(query *tb.Query) {
|
||||
ctx := context.Background()
|
||||
ctx, err := interceptQuery(context.Background(), query, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
defer interceptQuery(ctx, query, hm.onDefer)
|
||||
hm.handler(ctx, query)
|
||||
_, err = interceptQuery(ctx, query, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
+109
-119
@@ -3,10 +3,9 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/once"
|
||||
|
||||
@@ -16,10 +15,21 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
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
|
||||
OnDefer []intercept.Func
|
||||
@@ -27,38 +37,27 @@ type Interceptor struct {
|
||||
|
||||
// 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))
|
||||
func (bot TipBot) singletonCallbackInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
switch i.(type) {
|
||||
case *tb.Callback:
|
||||
c := i.(*tb.Callback)
|
||||
return ctx, once.Once(c.Data, strconv.FormatInt(c.Sender.ID, 10))
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
|
||||
// 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)
|
||||
return ctx, invalidTypeError
|
||||
}
|
||||
|
||||
// unlockInterceptor invoked as onDefer interceptor
|
||||
func (bot TipBot) unlockInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
user := ctx.Sender()
|
||||
func (bot TipBot) unlockInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
user := getTelegramUserFromInterface(i)
|
||||
if user != nil {
|
||||
mutex.Unlock(strconv.FormatInt(user.ID, 10))
|
||||
return ctx, nil
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
return ctx, invalidTypeError
|
||||
}
|
||||
func (bot TipBot) idInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
ctx.Context = context.WithValue(ctx, "uid", RandStringRunes(64))
|
||||
return ctx, nil
|
||||
func (bot TipBot) idInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
return context.WithValue(ctx, "uid", RandStringRunes(64)), nil
|
||||
}
|
||||
|
||||
// answerCallbackInterceptor will answer the callback with the given text in the context
|
||||
func (bot TipBot) answerCallbackInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
switch i.(type) {
|
||||
case *tb.Callback:
|
||||
@@ -68,153 +67,144 @@ func (bot TipBot) answerCallbackInterceptor(ctx context.Context, i interface{})
|
||||
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)
|
||||
return ctx, invalidTypeError
|
||||
}
|
||||
|
||||
// lockInterceptor invoked as first before interceptor
|
||||
func (bot TipBot) lockInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
user := getTelegramUserFromInterface(i)
|
||||
if user != nil {
|
||||
mutex.Lock(strconv.FormatInt(user.ID, 10))
|
||||
return ctx, nil
|
||||
}
|
||||
return nil, 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) {
|
||||
func (bot TipBot) requireUserInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
var user *lnbits.User
|
||||
var err error
|
||||
u := ctx.Sender()
|
||||
u := getTelegramUserFromInterface(i)
|
||||
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 context.WithValue(ctx, "user", user), err
|
||||
}
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
return nil, 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)
|
||||
}
|
||||
func (bot TipBot) loadUserInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
ctx, _ = bot.requireUserInterceptor(ctx, i)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// loadReplyToInterceptor Loading the Telegram user with message intercept
|
||||
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
|
||||
// getTelegramUserFromInterface returns the tb user based in interface type
|
||||
func getTelegramUserFromInterface(i interface{}) (user *tb.User) {
|
||||
switch i.(type) {
|
||||
case *tb.Query:
|
||||
user = &i.(*tb.Query).From
|
||||
case *tb.Callback:
|
||||
user = i.(*tb.Callback).Sender
|
||||
case *tb.Message:
|
||||
user = i.(*tb.Message).Sender
|
||||
default:
|
||||
log.Tracef("[getTelegramUserFromInterface] invalid type %s", reflect.TypeOf(i).String())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
return ctx, invalidTypeError
|
||||
}
|
||||
|
||||
func (bot TipBot) localizerInterceptor(ctx intercept.Context) (intercept.Context, error) {
|
||||
func (bot TipBot) localizerInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
var userLocalizer *i18n2.Localizer
|
||||
var publicLocalizer *i18n2.Localizer
|
||||
|
||||
// default language is english
|
||||
publicLocalizer = i18n2.NewLocalizer(i18n.Bundle, "en")
|
||||
ctx.Context = context.WithValue(ctx, "publicLanguageCode", "en")
|
||||
ctx.Context = context.WithValue(ctx, "publicLocalizer", publicLocalizer)
|
||||
ctx = context.WithValue(ctx, "publicLanguageCode", "en")
|
||||
ctx = context.WithValue(ctx, "publicLocalizer", publicLocalizer)
|
||||
|
||||
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() {
|
||||
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() {
|
||||
// in pm overwrite public localizer with user localizer
|
||||
ctx.Context = context.WithValue(ctx, "publicLanguageCode", ctx.Message().Sender.LanguageCode)
|
||||
ctx.Context = context.WithValue(ctx, "publicLocalizer", userLocalizer)
|
||||
ctx = context.WithValue(ctx, "publicLanguageCode", m.Sender.LanguageCode)
|
||||
ctx = context.WithValue(ctx, "publicLocalizer", userLocalizer)
|
||||
}
|
||||
return ctx, 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
|
||||
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
|
||||
}
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
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")
|
||||
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("[requirePrivateChatInterceptor] no private chat")
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
return nil, invalidTypeError
|
||||
}
|
||||
|
||||
const photoTag = "<Photo>"
|
||||
|
||||
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))
|
||||
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))
|
||||
}
|
||||
log.Infof(log_string)
|
||||
} 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)
|
||||
} 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)
|
||||
}
|
||||
return ctx, nil
|
||||
} else if ctx.Callback() != nil {
|
||||
log.Infof("[Callback %s:%d] Data: %s", GetUserStr(ctx.Callback().Sender), ctx.Callback().Sender.ID, ctx.Callback().Data)
|
||||
case *tb.Callback:
|
||||
m := i.(*tb.Callback)
|
||||
log.Infof("[Callback %s:%d] Data: %s", GetUserStr(m.Sender), m.Sender.ID, m.Data)
|
||||
return ctx, nil
|
||||
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
return nil, invalidTypeError
|
||||
}
|
||||
|
||||
// LoadUser from context
|
||||
|
||||
@@ -7,11 +7,6 @@ import (
|
||||
"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"
|
||||
@@ -21,25 +16,18 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type InvoiceEventCallback map[int]EventHandler
|
||||
|
||||
type EventHandler struct {
|
||||
Function func(event Event)
|
||||
Type EventType
|
||||
}
|
||||
type InvoiceEventCallback map[int]func(*InvoiceEvent)
|
||||
|
||||
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},
|
||||
InvoiceCallbackGeneric: bot.notifyInvoiceReceivedEvent,
|
||||
InvoiceCallbackInlineReceive: bot.inlineReceiveEvent,
|
||||
InvoiceCallbackLNURLPayReceive: bot.lnurlReceiveEvent,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,24 +37,8 @@ const (
|
||||
InvoiceCallbackGeneric = iota + 1
|
||||
InvoiceCallbackInlineReceive
|
||||
InvoiceCallbackLNURLPayReceive
|
||||
InvoiceCallbackGroupTicket
|
||||
InvoiceCallbackSatdressProxy
|
||||
)
|
||||
|
||||
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"`
|
||||
@@ -75,23 +47,12 @@ type Invoice struct {
|
||||
}
|
||||
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
|
||||
User *lnbits.User `json:"user"`
|
||||
Message *tb.Message `json:"message"`
|
||||
InvoiceMessage *tb.Message `json:"invoice_message"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
Callback int `json:"func"`
|
||||
CallbackData string `json:"callbackdata"`
|
||||
}
|
||||
|
||||
func (invoiceEvent InvoiceEvent) Key() string {
|
||||
@@ -106,26 +67,25 @@ func helpInvoiceUsage(ctx context.Context, errormsg string) string {
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
func (bot *TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx)
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
userStr := GetUserStr(user.Telegram)
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(m)
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
return
|
||||
}
|
||||
// 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
|
||||
_, err = bot.askForAmount(ctx, "", "CreateInvoiceState", 0, 0, m.Text)
|
||||
return ctx, err
|
||||
bot.askForAmount(ctx, "", "CreateInvoiceState", 0, 0, m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// check for memo in command
|
||||
@@ -140,14 +100,14 @@ func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, err
|
||||
memo = memo + tag
|
||||
}
|
||||
|
||||
creatingMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
log.Debugf("[/invoice] Creating invoice for %s of %d sat.", userStr, amount)
|
||||
creatingMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
log.Infof("[/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
|
||||
return
|
||||
}
|
||||
|
||||
// create qr code
|
||||
@@ -156,7 +116,7 @@ func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, err
|
||||
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
|
||||
return
|
||||
}
|
||||
|
||||
// deleting messages will delete the main menu.
|
||||
@@ -165,7 +125,7 @@ func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, err
|
||||
// send the invoice data to user
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
log.Printf("[/invoice] Incvoice created. User: %s, amount: %d sat.", userStr, amount)
|
||||
return ctx, nil
|
||||
return
|
||||
}
|
||||
|
||||
func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User, amount int64, memo string, callback int, callbackData string) (InvoiceEvent, error) {
|
||||
@@ -196,15 +156,7 @@ func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User
|
||||
return invoiceEvent, nil
|
||||
}
|
||||
|
||||
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("could not get balance of user %s", GetUserStr(invoiceEvent.User.Telegram))
|
||||
log.Errorln(errmsg)
|
||||
}
|
||||
|
||||
func (bot *TipBot) notifyInvoiceReceivedEvent(invoiceEvent *InvoiceEvent) {
|
||||
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
|
||||
}
|
||||
|
||||
@@ -215,29 +167,20 @@ type LNURLInvoice struct {
|
||||
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)
|
||||
|
||||
func (bot *TipBot) lnurlReceiveEvent(invoiceEvent *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.trySendMessage(tx.User.Telegram, fmt.Sprintf(`✉️ %s`, str.MarkdownEscape(tx.Comment)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+11
-13
@@ -2,26 +2,25 @@ package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"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/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot *TipBot) lndhubHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
|
||||
if internal.Configuration.Lnbits.LnbitsPublicUrl == "" {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "couldNotLinkMessage"))
|
||||
return ctx, fmt.Errorf("invalid configuration")
|
||||
return
|
||||
}
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx)
|
||||
bot.anyTextHandler(ctx, m)
|
||||
// reply only in private message
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
@@ -32,9 +31,8 @@ func (bot *TipBot) lndhubHandler(ctx intercept.Context) (intercept.Context, erro
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "walletConnectMessage"))
|
||||
|
||||
// do not respond to banned users
|
||||
if bot.UserIsBanned(fromUser) {
|
||||
log.Warnln("[lndhubHandler] user is banned. not responding.")
|
||||
return ctx, fmt.Errorf("user is banned")
|
||||
if strings.HasPrefix(fromUser.Wallet.Adminkey, "banned") || strings.HasPrefix(fromUser.Wallet.Adminkey, "_") {
|
||||
return
|
||||
}
|
||||
|
||||
lndhubUrl := fmt.Sprintf("lndhub://admin:%s@%slndhub/ext/", fromUser.Wallet.Adminkey, internal.Configuration.Lnbits.LnbitsPublicUrl)
|
||||
@@ -44,7 +42,7 @@ func (bot *TipBot) lndhubHandler(ctx intercept.Context) (intercept.Context, erro
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
// send the link to the user
|
||||
@@ -53,9 +51,9 @@ func (bot *TipBot) lndhubHandler(ctx intercept.Context) (intercept.Context, erro
|
||||
go func() {
|
||||
time.Sleep(time.Second * 60)
|
||||
bot.tryDeleteMessage(linkmsg)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "linkHiddenMessage"), tb.Silent)
|
||||
}()
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "linkHiddenMessage"))
|
||||
// auto delete the message
|
||||
// NewMessage(linkmsg, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
|
||||
return ctx, nil
|
||||
|
||||
}
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
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, lnurlAuthState.Message.Text, 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.GetHttpClient()
|
||||
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, lnurlAuthState.Message.Text, Translate(ctx, "lnurlSuccessfulLogin"))
|
||||
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)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
@@ -8,10 +9,6 @@ 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"
|
||||
|
||||
@@ -20,6 +17,7 @@ import (
|
||||
|
||||
lnurl "github.com/fiatjaf/go-lnurl"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
// LnurlPayState saves the state of the user for an LNURL payment
|
||||
@@ -35,17 +33,19 @@ type LnurlPayState struct {
|
||||
|
||||
// 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) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPayState) {
|
||||
m := ctx.Message()
|
||||
func (bot *TipBot) lnurlPayHandler(ctx context.Context, m *tb.Message, payParams LnurlPayState) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
}
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("lnurlp-%d-%s", m.Sender.ID, RandStringRunes(5))
|
||||
payParams.Base = storage.New(storage.ID(id))
|
||||
payParams.From = user
|
||||
payParams.LanguageCode = ctx.Value("publicLanguageCode").(string)
|
||||
lnurlPayState := &LnurlPayState{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
From: user,
|
||||
LNURLPayParams: payParams.LNURLPayParams,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
|
||||
// first we check whether an amount is present in the command
|
||||
amount, amount_err := decodeAmountFromCommand(m.Text)
|
||||
@@ -60,42 +60,39 @@ func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPaySta
|
||||
// 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) > int(lnurlPayState.LNURLPayParams.CommentAllowed) {
|
||||
memo = memo[:lnurlPayState.LNURLPayParams.CommentAllowed]
|
||||
}
|
||||
if len(memo) > 0 {
|
||||
payParams.Comment = memo
|
||||
lnurlPayState.Comment = memo
|
||||
}
|
||||
|
||||
// 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) > (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
|
||||
(int64(amount) > (lnurlPayState.LNURLPayParams.MaxSendable/1000) || int64(amount) < (lnurlPayState.LNURLPayParams.MinSendable/1000)) &&
|
||||
(lnurlPayState.LNURLPayParams.MaxSendable != 0 && lnurlPayState.LNURLPayParams.MinSendable != 0) { // only if max and min are set
|
||||
err := fmt.Errorf("amount not in range")
|
||||
log.Warnf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), payParams.LNURLPayParams.MinSendable/1000, payParams.LNURLPayParams.MaxSendable/1000))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), lnurlPayState.LNURLPayParams.MinSendable/1000, lnurlPayState.LNURLPayParams.MaxSendable/1000))
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
}
|
||||
// set also amount in the state of the user
|
||||
payParams.Amount = amount * 1000 // save as mSat
|
||||
lnurlPayState.Amount = amount * 1000 // save as mSat
|
||||
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(payParams.Set(payParams, bot.Bunt))
|
||||
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
|
||||
|
||||
// now we actualy check whether the amount was in the command and if not, ask for it
|
||||
if 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 {
|
||||
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)
|
||||
bot.askForAmount(ctx, id, "LnurlPayState", lnurlPayState.LNURLPayParams.MinSendable, lnurlPayState.LNURLPayParams.MaxSendable, m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// We need to save the pay state in the user state so we can load the payment in the next ctx
|
||||
paramsJson, err := json.Marshal(payParams)
|
||||
// We need to save the pay state in the user state so we can load the payment in the next handler
|
||||
paramsJson, err := json.Marshal(lnurlPayState)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
@@ -103,16 +100,15 @@ func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPaySta
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
|
||||
// directly go to confirm
|
||||
bot.lnurlPayHandlerSend(ctx)
|
||||
bot.lnurlPayHandlerSend(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
// 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()
|
||||
func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
|
||||
@@ -120,7 +116,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
if user.StateKey != lnbits.UserHasEnteredAmount {
|
||||
log.Errorln("[lnurlPayHandlerSend] state keys don't match")
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, fmt.Errorf("wrong state key")
|
||||
return
|
||||
}
|
||||
|
||||
// read the enter amount state from user.StateData
|
||||
@@ -129,8 +125,9 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
// use the enter amount state of the user to load the LNURL payment state
|
||||
tx := &LnurlPayState{Base: storage.New(storage.ID(enterAmountData.ID))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
@@ -139,23 +136,23 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
lnurlPayState := fn.(*LnurlPayState)
|
||||
|
||||
// LnurlPayState loaded
|
||||
|
||||
client, err := network.GetHttpClient()
|
||||
client, err := bot.GetHttpClient()
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
qs := callbackUrl.Query()
|
||||
// add amount to query string
|
||||
@@ -171,13 +168,13 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
body, err := ioutil.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
var response2 lnurl.LNURLPayValues
|
||||
@@ -189,7 +186,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
}
|
||||
log.Errorf("[lnurlPayHandler] Error in LNURLPayValues: %s", error_reason)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
|
||||
return ctx, fmt.Errorf("Error in LNURLPayValues: %s", error_reason)
|
||||
return
|
||||
}
|
||||
|
||||
lnurlPayState.LNURLPayValues = response2
|
||||
@@ -197,14 +194,13 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
|
||||
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
|
||||
bot.Telegram.Delete(statusMsg)
|
||||
m.Text = fmt.Sprintf("/pay %s", response2.PR)
|
||||
return bot.payHandler(ctx)
|
||||
bot.payHandler(ctx, m)
|
||||
}
|
||||
|
||||
func (bot *TipBot) sendToLightningAddress(ctx intercept.Context, address string, amount int64) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, address string, amount int64) error {
|
||||
split := strings.Split(address, "@")
|
||||
if len(split) != 2 {
|
||||
return ctx, fmt.Errorf("lightning address format wrong")
|
||||
return fmt.Errorf("lightning address format wrong")
|
||||
}
|
||||
host := strings.ToLower(split[1])
|
||||
name := strings.ToLower(split[0])
|
||||
@@ -216,7 +212,7 @@ func (bot *TipBot) sendToLightningAddress(ctx intercept.Context, address string,
|
||||
|
||||
lnurl, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
return err
|
||||
}
|
||||
|
||||
if amount > 0 {
|
||||
@@ -236,5 +232,6 @@ func (bot *TipBot) sendToLightningAddress(ctx intercept.Context, address string,
|
||||
// this will invoke the "enter amount" dialog in the lnurl handler
|
||||
m.Text = fmt.Sprintf("/lnurl %s", lnurl)
|
||||
}
|
||||
return bot.lnurlHandler(ctx)
|
||||
bot.lnurlHandler(ctx, m)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -7,11 +7,6 @@ import (
|
||||
"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"
|
||||
|
||||
@@ -23,11 +18,11 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
lnurl "github.com/fiatjaf/go-lnurl"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
withdrawConfirmationMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
withdrawConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelWithdraw = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_withdraw")
|
||||
btnWithdraw = paymentConfirmationMenu.Data("✅ Withdraw", "confirm_withdraw")
|
||||
)
|
||||
@@ -46,7 +41,6 @@ type LnurlWithdrawState struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// editSingleButton edits a message to display a single button (for something like a progress indicator)
|
||||
func (bot *TipBot) editSingleButton(ctx context.Context, m *tb.Message, message string, button string) {
|
||||
bot.tryEditMessage(
|
||||
m,
|
||||
@@ -61,18 +55,19 @@ func (bot *TipBot) editSingleButton(ctx context.Context, m *tb.Message, message
|
||||
|
||||
// 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()
|
||||
func (bot *TipBot) lnurlWithdrawHandler(ctx context.Context, m *tb.Message, withdrawParams LnurlWithdrawState) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
}
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("lnurlw-%d-%s", m.Sender.ID, RandStringRunes(5))
|
||||
|
||||
withdrawParams.Base = storage.New(storage.ID(id))
|
||||
withdrawParams.From = user
|
||||
withdrawParams.LanguageCode = ctx.Value("publicLanguageCode").(string)
|
||||
LnurlWithdrawState := LnurlWithdrawState{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
From: user,
|
||||
LNURLWithdrawResponse: withdrawParams.LNURLWithdrawResponse,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
|
||||
// first we check whether an amount is present in the command
|
||||
amount, amount_err := decodeAmountFromCommand(m.Text)
|
||||
@@ -80,36 +75,36 @@ func (bot *TipBot) lnurlWithdrawHandler(ctx intercept.Context, withdrawParams *L
|
||||
// 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
|
||||
(int64(amount) > (LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable/1000) || int64(amount) < (LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable/1000)) &&
|
||||
(LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable != 0 && LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable != 0) { // only if max and min are set
|
||||
err := fmt.Errorf("amount not in range")
|
||||
log.Warnf("[lnurlWithdrawHandler] Error: %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), withdrawParams.LNURLWithdrawResponse.MinWithdrawable/1000, withdrawParams.LNURLWithdrawResponse.MaxWithdrawable/1000))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable/1000, LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable/1000))
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
}
|
||||
|
||||
// if no amount is entered, and if only one amount is possible, we use it
|
||||
if amount_err != nil && withdrawParams.LNURLWithdrawResponse.MaxWithdrawable == withdrawParams.LNURLWithdrawResponse.MinWithdrawable {
|
||||
amount = int64(withdrawParams.LNURLWithdrawResponse.MaxWithdrawable / 1000)
|
||||
if amount_err != nil && LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable == LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable {
|
||||
amount = int64(LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable / 1000)
|
||||
amount_err = nil
|
||||
}
|
||||
|
||||
// set also amount in the state of the user
|
||||
withdrawParams.Amount = amount * 1000 // save as mSat
|
||||
LnurlWithdrawState.Amount = amount * 1000 // save as mSat
|
||||
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(withdrawParams.Set(withdrawParams, bot.Bunt))
|
||||
runtime.IgnoreError(LnurlWithdrawState.Set(LnurlWithdrawState, bot.Bunt))
|
||||
|
||||
// now we actualy check whether the amount was in the command and if not, ask for it
|
||||
if amount_err != nil || amount < 1 {
|
||||
// // no amount was entered, set user state and ask for amount
|
||||
bot.askForAmount(ctx, id, "LnurlWithdrawState", withdrawParams.LNURLWithdrawResponse.MinWithdrawable, withdrawParams.LNURLWithdrawResponse.MaxWithdrawable, m.Text)
|
||||
bot.askForAmount(ctx, id, "LnurlWithdrawState", LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable, LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable, m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// We need to save the pay state in the user state so we can load the payment in the next ctx
|
||||
paramsJson, err := json.Marshal(withdrawParams)
|
||||
// We need to save the pay state in the user state so we can load the payment in the next handler
|
||||
paramsJson, err := json.Marshal(LnurlWithdrawState)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandler] Error: %s", err.Error())
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
@@ -117,24 +112,23 @@ func (bot *TipBot) lnurlWithdrawHandler(ctx intercept.Context, withdrawParams *L
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
|
||||
// directly go to confirm
|
||||
bot.lnurlWithdrawHandlerWithdraw(ctx)
|
||||
bot.lnurlWithdrawHandlerWithdraw(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
// lnurlWithdrawHandlerWithdraw is invoked when the user has delivered an amount and is ready to pay
|
||||
func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
statusMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "lnurlPreparingWithdraw"))
|
||||
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlPreparingWithdraw"))
|
||||
|
||||
// assert that user has entered an amount
|
||||
if user.StateKey != lnbits.UserHasEnteredAmount {
|
||||
log.Errorln("[lnurlWithdrawHandlerWithdraw] state keys don't match")
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, fmt.Errorf("wrong state key")
|
||||
return
|
||||
}
|
||||
|
||||
// read the enter amount state from user.StateData
|
||||
@@ -143,7 +137,7 @@ func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx intercept.Context) (intercep
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
// use the enter amount state of the user to load the LNURL payment state
|
||||
@@ -154,7 +148,7 @@ func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx intercept.Context) (intercep
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
var lnurlWithdrawState *LnurlWithdrawState
|
||||
switch fn.(type) {
|
||||
@@ -163,7 +157,7 @@ func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx intercept.Context) (intercep
|
||||
default:
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] invalid type")
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, fmt.Errorf("invalid type")
|
||||
return
|
||||
}
|
||||
|
||||
confirmText := fmt.Sprintf(Translate(ctx, "confirmLnurlWithdrawMessage"), lnurlWithdrawState.Amount/1000)
|
||||
@@ -173,8 +167,10 @@ func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx intercept.Context) (intercep
|
||||
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)
|
||||
withdrawButton := paymentConfirmationMenu.Data(Translate(ctx, "withdrawButtonMessage"), "confirm_withdraw")
|
||||
btnCancelWithdraw := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_withdraw")
|
||||
withdrawButton.Data = lnurlWithdrawState.ID
|
||||
btnCancelWithdraw.Data = lnurlWithdrawState.ID
|
||||
|
||||
withdrawConfirmationMenu.Inline(
|
||||
withdrawConfirmationMenu.Row(
|
||||
@@ -187,19 +183,17 @@ func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx intercept.Context) (intercep
|
||||
// // 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()
|
||||
func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.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
|
||||
return
|
||||
}
|
||||
|
||||
var lnurlWithdrawState *LnurlWithdrawState
|
||||
@@ -208,24 +202,24 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
|
||||
lnurlWithdrawState = fn.(*LnurlWithdrawState)
|
||||
default:
|
||||
log.Errorf("[confirmWithdrawHandler] invalid type")
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
return
|
||||
}
|
||||
// onnly the correct user can press
|
||||
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
return
|
||||
}
|
||||
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)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
}
|
||||
defer lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt)
|
||||
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
bot.tryDeleteMessage(c)
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
}
|
||||
|
||||
// reset state immediately
|
||||
@@ -237,9 +231,9 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
|
||||
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.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
// generate an invoice and add the pr to the request
|
||||
@@ -255,7 +249,7 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
|
||||
errmsg := fmt.Sprintf("[lnurlWithdrawHandlerWithdraw] Could not create an invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
lnurlWithdrawState.Invoice = invoice
|
||||
|
||||
@@ -266,26 +260,26 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
|
||||
callbackUrl.RawQuery = qs.Encode()
|
||||
|
||||
// lnurlWithdrawState loaded
|
||||
client, err := network.GetHttpClient()
|
||||
client, err := bot.GetHttpClient()
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
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.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
return ctx, errors.New(errors.UnknownError, err)
|
||||
return
|
||||
}
|
||||
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.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
// parse the response
|
||||
@@ -299,18 +293,17 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] LNURLWithdraw failed.")
|
||||
// update button text
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawFailed"))
|
||||
return ctx, errors.New(errors.UnknownError, fmt.Errorf("LNURLWithdraw failed"))
|
||||
return
|
||||
}
|
||||
|
||||
// add response to persistent struct
|
||||
lnurlWithdrawState.LNURResponse = response2
|
||||
return ctx, lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt)
|
||||
runtime.IgnoreError(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()
|
||||
func (bot *TipBot) cancelWithdrawHandler(ctx context.Context, c *tb.Callback) {
|
||||
// reset state immediately
|
||||
user := LoadUser(ctx)
|
||||
ResetUserState(user, bot)
|
||||
@@ -320,7 +313,7 @@ func (bot *TipBot) cancelWithdrawHandler(ctx intercept.Context) (intercept.Conte
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelWithdrawHandler] Error: %s", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
var lnurlWithdrawState *LnurlWithdrawState
|
||||
switch fn.(type) {
|
||||
@@ -331,8 +324,8 @@ func (bot *TipBot) cancelWithdrawHandler(ctx intercept.Context) (intercept.Conte
|
||||
}
|
||||
// onnly the correct user can press
|
||||
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
return
|
||||
}
|
||||
bot.tryEditMessage(c, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawCancelled"), &tb.ReplyMarkup{})
|
||||
return ctx, lnurlWithdrawState.Inactivate(lnurlWithdrawState, bot.Bunt)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawCancelled"), &tb.ReplyMarkup{})
|
||||
lnurlWithdrawState.Inactivate(lnurlWithdrawState, bot.Bunt)
|
||||
}
|
||||
|
||||
+49
-66
@@ -2,16 +2,14 @@ package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"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"
|
||||
|
||||
@@ -19,33 +17,45 @@ import (
|
||||
lnurl "github.com/fiatjaf/go-lnurl"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
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) {
|
||||
}
|
||||
|
||||
// lnurlHandler is invoked on /lnurl command
|
||||
func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) {
|
||||
// commands:
|
||||
// /lnurl
|
||||
// /lnurl <LNURL>
|
||||
// or /lnurl <amount> <LNURL>
|
||||
m := ctx.Message()
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
return
|
||||
}
|
||||
log.Infof("[lnurlHandler] %s", m.Text)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
|
||||
// if only /lnurl is entered, show the lnurl of the user
|
||||
if m.Text == "/lnurl" {
|
||||
return bot.lnurlReceiveHandler(ctx)
|
||||
bot.lnurlReceiveHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
statusMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "lnurlResolvingUrlMessage"))
|
||||
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlResolvingUrlMessage"))
|
||||
|
||||
var lnurlSplit string
|
||||
split := strings.Split(m.Text, " ")
|
||||
@@ -59,62 +69,39 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error
|
||||
} 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)
|
||||
return
|
||||
}
|
||||
|
||||
// get rid of the URI prefix
|
||||
lnurlSplit = strings.TrimPrefix(lnurlSplit, "lightning:")
|
||||
|
||||
log.Debugf("[lnurlHandler] lnurlSplit: %s", lnurlSplit)
|
||||
// HandleLNURL by fiatjaf/go-lnurl
|
||||
_, params, err := bot.HandleLNURL(lnurlSplit)
|
||||
if err != nil {
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "LNURL error."))
|
||||
// bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
log.Warnf("[HandleLNURL] Error: %s", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
switch params.(type) {
|
||||
case lnurl.LNURLAuthParams:
|
||||
authParams := &LnurlAuthState{LNURLAuthParams: params.(lnurl.LNURLAuthParams)}
|
||||
log.Infof("[LNURL-auth] %s", authParams.LNURLAuthParams.Callback)
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
ctx.Context, err = bot.lnurlAuthHandler(ctx, m, authParams)
|
||||
return ctx, err
|
||||
|
||||
case lnurl.LNURLPayParams:
|
||||
payParams := &LnurlPayState{LNURLPayParams: params.(lnurl.LNURLPayParams)}
|
||||
log.Infof("[LNURL-p] %s", payParams.LNURLPayParams.Callback)
|
||||
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: fmt.Sprintf("%s", 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)
|
||||
|
||||
bot.lnurlPayHandler(ctx, m, *payParams)
|
||||
return
|
||||
case lnurl.LNURLWithdrawResponse:
|
||||
withdrawParams := &LnurlWithdrawState{LNURLWithdrawResponse: params.(lnurl.LNURLWithdrawResponse)}
|
||||
withdrawParams := LnurlWithdrawState{LNURLWithdrawResponse: params.(lnurl.LNURLWithdrawResponse)}
|
||||
log.Infof("[LNURL-w] %s", withdrawParams.LNURLWithdrawResponse.Callback)
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
bot.lnurlWithdrawHandler(ctx, withdrawParams)
|
||||
bot.lnurlWithdrawHandler(ctx, m, withdrawParams)
|
||||
default:
|
||||
if err == nil {
|
||||
err = fmt.Errorf("invalid LNURL type")
|
||||
err = errors.New("Invalid LNURL type.")
|
||||
}
|
||||
log.Warnln(err)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) UserGetLightningAddress(user *lnbits.User) (string, error) {
|
||||
@@ -127,12 +114,20 @@ 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.AnonIDSha256), strings.ToLower(internal.Configuration.Bot.LNURLHostUrl.Hostname())), nil
|
||||
return fmt.Sprintf("%s@%s", fmt.Sprint(user.AnonID), strings.ToLower(internal.Configuration.Bot.LNURLHostUrl.Hostname())), nil
|
||||
}
|
||||
|
||||
func UserGetLNURL(user *lnbits.User) (string, error) {
|
||||
name := fmt.Sprint(user.UUID)
|
||||
// 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)
|
||||
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 {
|
||||
@@ -141,38 +136,26 @@ func UserGetLNURL(user *lnbits.User) (string, error) {
|
||||
return lnurlEncode, nil
|
||||
}
|
||||
|
||||
func UserGetAnonLNURL(user *lnbits.User) (string, error) {
|
||||
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, fmt.Sprint(user.AnonIDSha256))
|
||||
lnurlEncode, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return lnurlEncode, nil
|
||||
}
|
||||
|
||||
// lnurlReceiveHandler outputs the LNURL of the user
|
||||
func (bot TipBot) lnurlReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
func (bot TipBot) lnurlReceiveHandler(ctx context.Context, m *tb.Message) {
|
||||
fromUser := LoadUser(ctx)
|
||||
lnurlEncode, err := UserGetLNURL(fromUser)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to get LNURL: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlNoUsernameMessage"))
|
||||
return ctx, err
|
||||
bot.Telegram.Send(m.Sender, Translate(ctx, "lnurlNoUsernameMessage"))
|
||||
}
|
||||
// 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.Error())
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlReceiveInfoText"))
|
||||
// send the lnurl QR code
|
||||
// send the lnurl data to user
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lnurlEncode)})
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// fiatjaf/go-lnurl 1.8.4 with proxy
|
||||
@@ -205,7 +188,7 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
lnurl_str, ok := lnurl.FindLNURLInText(rawlnurl)
|
||||
if !ok {
|
||||
return "", nil,
|
||||
fmt.Errorf("invalid bech32-encoded lnurl: " + rawlnurl)
|
||||
errors.New("invalid bech32-encoded lnurl: " + rawlnurl)
|
||||
}
|
||||
rawurl, err = lnurl.LNURLDecode(lnurl_str)
|
||||
if err != nil {
|
||||
@@ -236,7 +219,7 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
// return rawurl, nil, err
|
||||
// }
|
||||
|
||||
client, err := network.GetHttpClient()
|
||||
client, err := bot.GetHttpClient()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
@@ -245,7 +228,7 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
return rawurl, nil, err
|
||||
}
|
||||
if resp.StatusCode >= 300 {
|
||||
return rawurl, nil, fmt.Errorf("HTTP error: " + resp.Status)
|
||||
return rawurl, nil, errors.New("HTTP error: " + resp.Status)
|
||||
}
|
||||
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
@@ -273,6 +256,6 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
// value, err := lnurl.HandleChannel(b)
|
||||
// return rawurl, value, err
|
||||
default:
|
||||
return rawurl, nil, fmt.Errorf("Unkown LNURL response.")
|
||||
return rawurl, nil, errors.New("Unkown LNURL response.")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
|
||||
+59
-75
@@ -3,11 +3,8 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
@@ -18,11 +15,11 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
decodepay "github.com/fiatjaf/ln-decodepay"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
paymentConfirmationMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
paymentConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelPay = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_pay")
|
||||
btnPay = paymentConfirmationMenu.Data("✅ Pay", "confirm_pay")
|
||||
)
|
||||
@@ -49,26 +46,26 @@ type PayData struct {
|
||||
}
|
||||
|
||||
// payHandler invoked on "/pay lnbc..." command
|
||||
func (bot *TipBot) payHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx)
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
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)
|
||||
if len(strings.Split(m.Text, " ")) < 2 {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, ""))
|
||||
return
|
||||
}
|
||||
userStr := GetUserStr(ctx.Sender())
|
||||
paymentRequest, err := getArgumentFromCommand(ctx.Message().Text, 1)
|
||||
userStr := GetUserStr(m.Sender)
|
||||
paymentRequest, err := getArgumentFromCommand(m.Text, 1)
|
||||
if err != nil {
|
||||
NewMessage(ctx.Message(), WithDuration(0, bot))
|
||||
bot.trySendMessage(ctx.Sender(), helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not getArgumentFromCommand: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return ctx, errors.New(errors.InvalidSyntaxError, err)
|
||||
return
|
||||
}
|
||||
paymentRequest = strings.ToLower(paymentRequest)
|
||||
// get rid of the URI prefix
|
||||
@@ -77,38 +74,38 @@ func (bot *TipBot) payHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
// decode invoice
|
||||
bolt11, err := decodepay.Decodepay(paymentRequest)
|
||||
if err != nil {
|
||||
bot.trySendMessage(ctx.Sender(), helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
|
||||
bot.trySendMessage(m.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)
|
||||
return
|
||||
}
|
||||
amount := int64(bolt11.MSatoshi / 1000)
|
||||
|
||||
if amount <= 0 {
|
||||
bot.trySendMessage(ctx.Sender(), Translate(ctx, "invoiceNoAmountMessage"))
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "invoiceNoAmountMessage"))
|
||||
errmsg := fmt.Sprint("[/pay] Error: invoice without amount")
|
||||
log.Warnln(errmsg)
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
return
|
||||
}
|
||||
|
||||
// check user balance first
|
||||
balance, err := bot.GetUserBalance(user)
|
||||
if err != nil {
|
||||
NewMessage(ctx.Message(), WithDuration(0, bot))
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
bot.trySendMessage(ctx.Sender(), Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, errors.New(errors.GetBalanceError, err)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
if amount > balance {
|
||||
NewMessage(ctx.Message(), WithDuration(0, bot))
|
||||
bot.trySendMessage(ctx.Sender(), fmt.Sprintf(Translate(ctx, "insufficientFundsMessage"), balance, amount))
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "insufficientFundsMessage"), balance, amount))
|
||||
return
|
||||
}
|
||||
// send warning that the invoice might fail due to missing fee reserve
|
||||
if float64(amount) > float64(balance)*0.98 {
|
||||
bot.trySendMessage(ctx.Sender(), Translate(ctx, "feeReserveMessage"))
|
||||
if float64(amount) > float64(balance)*0.99 {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "feeReserveMessage"))
|
||||
}
|
||||
|
||||
confirmText := fmt.Sprintf(Translate(ctx, "confirmPayInvoiceMessage"), amount)
|
||||
@@ -119,18 +116,20 @@ func (bot *TipBot) payHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
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", ctx.Sender().ID, amount, RandStringRunes(5))
|
||||
id := fmt.Sprintf("pay-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
|
||||
|
||||
// // // create inline buttons
|
||||
payButton := paymentConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "confirm_pay", id)
|
||||
cancelButton := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_pay", id)
|
||||
payButton := paymentConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "confirm_pay")
|
||||
cancelButton := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_pay")
|
||||
payButton.Data = id
|
||||
cancelButton.Data = id
|
||||
|
||||
paymentConfirmationMenu.Inline(
|
||||
paymentConfirmationMenu.Row(
|
||||
payButton,
|
||||
cancelButton),
|
||||
)
|
||||
payMessage := bot.trySendMessageEditable(ctx.Chat(), confirmText, paymentConfirmationMenu)
|
||||
payMessage := bot.trySendMessage(m.Chat, confirmText, paymentConfirmationMenu)
|
||||
payData := &PayData{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
From: user,
|
||||
@@ -145,41 +144,40 @@ func (bot *TipBot) payHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
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 intercept.Context) (intercept.Context, error) {
|
||||
tx := &PayData{Base: storage.New(storage.ID(ctx.Data()))}
|
||||
func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &PayData{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
|
||||
return
|
||||
}
|
||||
payData := sn.(*PayData)
|
||||
|
||||
// onnly the correct user can press
|
||||
if payData.From.Telegram.ID != ctx.Sender().ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
if payData.From.Telegram.ID != c.Sender.ID {
|
||||
return
|
||||
}
|
||||
if !payData.Active {
|
||||
log.Errorf("[confirmPayHandler] send not active anymore")
|
||||
bot.tryEditMessage(ctx.Message(), i18n.Translate(payData.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
|
||||
bot.tryDeleteMessage(ctx.Message())
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
}
|
||||
defer payData.Set(payData, bot.Bunt)
|
||||
|
||||
// remove buttons from confirmation message
|
||||
// bot.tryEditMessage(handler.Message(), MarkdownEscape(payData.Message), &tb.ReplyMarkup{})
|
||||
// bot.tryEditMessage(c.Message, MarkdownEscape(payData.Message), &tb.ReplyMarkup{})
|
||||
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
bot.tryDeleteMessage(ctx.Message())
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
}
|
||||
|
||||
invoiceString := payData.Invoice
|
||||
@@ -187,11 +185,11 @@ func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context,
|
||||
// reset state immediately
|
||||
ResetUserState(user, bot)
|
||||
|
||||
userStr := GetUserStr(ctx.Sender())
|
||||
userStr := GetUserStr(c.Sender)
|
||||
|
||||
// update button text
|
||||
bot.tryEditMessage(
|
||||
ctx.Message(),
|
||||
c.Message,
|
||||
payData.Message,
|
||||
&tb.ReplyMarkup{
|
||||
InlineKeyboard: [][]tb.InlineButton{
|
||||
@@ -206,62 +204,48 @@ func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context,
|
||||
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(ctx.Message(), fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
|
||||
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)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
payData.Hash = invoice.PaymentHash
|
||||
|
||||
// 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 c.Message.Private() {
|
||||
// if the command was invoked in private chat
|
||||
// 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"))
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
|
||||
} else {
|
||||
// if the command was invoked in group chat
|
||||
bot.trySendMessage(ctx.Sender(), i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
|
||||
bot.tryEditMessage(ctx.Message(), fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePublicPaidMessage"), userStr), &tb.ReplyMarkup{})
|
||||
bot.trySendMessage(c.Sender, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
|
||||
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePublicPaidMessage"), userStr), &tb.ReplyMarkup{})
|
||||
}
|
||||
log.Infof("[⚡️ pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
|
||||
return ctx, nil
|
||||
return
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot *TipBot) cancelPaymentHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
func (bot *TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) {
|
||||
// reset state immediately
|
||||
user := LoadUser(ctx)
|
||||
ResetUserState(user, bot)
|
||||
tx := &PayData{Base: storage.New(storage.ID(ctx.Data()))}
|
||||
tx := &PayData{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("[cancelPaymentHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
payData := sn.(*PayData)
|
||||
// onnly the correct user can press
|
||||
if payData.From.Telegram.ID != ctx.Callback().Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
if payData.From.Telegram.ID != c.Sender.ID {
|
||||
return
|
||||
}
|
||||
// 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)
|
||||
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"), &tb.ReplyMarkup{})
|
||||
payData.Inactivate(payData, bot.Bunt)
|
||||
}
|
||||
|
||||
+17
-93
@@ -1,26 +1,20 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"strings"
|
||||
|
||||
"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/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
// TryRecognizeInvoiceFromQrCode will try to read an invoice string from a qr code and invoke the payment ctx.
|
||||
// TryRecognizeInvoiceFromQrCode will try to read an invoice string from a qr code and invoke the payment handler.
|
||||
func TryRecognizeQrCode(img image.Image) (*gozxing.Result, error) {
|
||||
// check for qr code
|
||||
bmp, _ := gozxing.NewBinaryBitmapFromImage(img)
|
||||
@@ -33,125 +27,55 @@ 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 ctx
|
||||
// invoke payment confirmation handler
|
||||
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 intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
func (bot *TipBot) photoHandler(ctx context.Context, m *tb.Message) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
return
|
||||
}
|
||||
if m.Photo == nil {
|
||||
return ctx, errors.Create(errors.NoPhotoError)
|
||||
return
|
||||
}
|
||||
user := LoadUser(ctx)
|
||||
if c := stateCallbackMessage[user.StateKey]; c != nil {
|
||||
ctx, err := c(ctx)
|
||||
c(ctx, m)
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
// get file reader closer from Telegram api
|
||||
reader, err := bot.Telegram.File(m.Photo.MediaFile())
|
||||
reader, err := bot.Telegram.GetFile(m.Photo.MediaFile())
|
||||
if err != nil {
|
||||
log.Errorf("[photoHandler] getfile error: %v\n", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
// decode to jpeg image
|
||||
img, err := jpeg.Decode(reader)
|
||||
if err != nil {
|
||||
log.Errorf("[photoHandler] image.Decode error: %v\n", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
data, err := TryRecognizeQrCode(img)
|
||||
if err != nil {
|
||||
log.Errorf("[photoHandler] tryRecognizeQrCodes error: %v\n", err.Error())
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "photoQrNotRecognizedMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
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())
|
||||
return bot.payHandler(ctx)
|
||||
bot.payHandler(ctx, m)
|
||||
return
|
||||
} else if lightning.IsLnurl(data.String()) {
|
||||
m.Text = fmt.Sprintf("/lnurl %s", data.String())
|
||||
return bot.lnurlHandler(ctx)
|
||||
bot.lnurlHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -1,556 +0,0 @@
|
||||
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
|
||||
}
|
||||
+67
-118
@@ -6,10 +6,6 @@ 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"
|
||||
|
||||
@@ -20,11 +16,11 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
sendConfirmationMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
sendConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelSend = sendConfirmationMenu.Data("🚫 Cancel", "cancel_send")
|
||||
btnSend = sendConfirmationMenu.Data("✅ Send", "confirm_send")
|
||||
)
|
||||
@@ -57,11 +53,11 @@ type SendData struct {
|
||||
}
|
||||
|
||||
// sendHandler invoked on "/send 123 @user" command
|
||||
func (bot *TipBot) sendHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
bot.anyTextHandler(ctx)
|
||||
func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
|
||||
// reset state immediately
|
||||
@@ -70,9 +66,9 @@ func (bot *TipBot) sendHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
// check and print all commands
|
||||
|
||||
// If the send is a reply, then trigger /tip handler
|
||||
if ctx.Message().IsReply() && ctx.Message().Chat.Type != tb.ChatPrivate {
|
||||
return bot.tipHandler(ctx)
|
||||
|
||||
if m.IsReply() && m.Chat.Type != tb.ChatPrivate {
|
||||
bot.tipHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
// if ok, errstr := bot.SendCheckSyntax(ctx, m); !ok {
|
||||
@@ -82,41 +78,41 @@ func (bot *TipBot) sendHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
// }
|
||||
|
||||
// get send amount, returns 0 if no amount is given
|
||||
amount, err := decodeAmountFromCommand(ctx.Text())
|
||||
amount, err := decodeAmountFromCommand(m.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
|
||||
|
||||
// CHECK whether first or second argument is a LIGHTNING ADDRESS
|
||||
arg := ""
|
||||
if len(strings.Split(ctx.Message().Text, " ")) > 2 {
|
||||
arg, err = getArgumentFromCommand(ctx.Message().Text, 2)
|
||||
} else if len(strings.Split(ctx.Message().Text, " ")) == 2 {
|
||||
arg, err = getArgumentFromCommand(ctx.Message().Text, 1)
|
||||
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)
|
||||
}
|
||||
if err == nil {
|
||||
if lightning.IsLightningAddress(arg) {
|
||||
// lightning address, send to that address
|
||||
ctx, err = bot.sendToLightningAddress(ctx, arg, amount)
|
||||
err = bot.sendToLightningAddress(ctx, m, arg, amount)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
return ctx, err
|
||||
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
|
||||
arg, err = getArgumentFromCommand(m.Text, 1)
|
||||
if err != nil && m.Chat.Type == tb.ChatPrivate {
|
||||
bot.askForUser(ctx, "", "CreateSendState", m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// is an amount given?
|
||||
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
|
||||
amount, err = decodeAmountFromCommand(m.Text)
|
||||
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
|
||||
bot.askForAmount(ctx, "", "CreateSendState", 0, 0, m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// ASSUME INTERNAL SEND TO TELEGRAM USER
|
||||
@@ -124,51 +120,51 @@ func (bot *TipBot) sendHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
errmsg := fmt.Sprintf("[/send] Error: Send amount not valid.")
|
||||
log.Warnln(errmsg)
|
||||
// immediately delete if the amount is bullshit
|
||||
NewMessage(ctx.Message(), WithDuration(0, bot))
|
||||
bot.trySendMessage(ctx.Sender(), helpSendUsage(ctx, Translate(ctx, "sendValidAmountMessage")))
|
||||
return ctx, err
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpSendUsage(ctx, Translate(ctx, "sendValidAmountMessage")))
|
||||
return
|
||||
}
|
||||
|
||||
// SEND COMMAND IS VALID
|
||||
// check for memo in command
|
||||
sendMemo := GetMemoFromCommand(ctx.Message().Text, 3)
|
||||
sendMemo := GetMemoFromCommand(m.Text, 3)
|
||||
|
||||
toUserStrMention := ""
|
||||
toUserStrWithoutAt := ""
|
||||
|
||||
// check for user in command, accepts user mention or plain username without @
|
||||
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]
|
||||
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]
|
||||
toUserStrWithoutAt = strings.TrimPrefix(toUserStrMention, "@")
|
||||
} else {
|
||||
toUserStrWithoutAt, err = getArgumentFromCommand(ctx.Message().Text, 2)
|
||||
toUserStrWithoutAt, err = getArgumentFromCommand(m.Text, 2)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
toUserStrWithoutAt = strings.TrimPrefix(toUserStrWithoutAt, "@")
|
||||
toUserStrMention = "@" + toUserStrWithoutAt
|
||||
}
|
||||
|
||||
err = bot.parseCmdDonHandler(ctx)
|
||||
err = bot.parseCmdDonHandler(ctx, m)
|
||||
if err == nil {
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
return
|
||||
}
|
||||
|
||||
toUserDb, err := GetUserByTelegramUsername(toUserStrWithoutAt, *bot)
|
||||
if err != nil {
|
||||
NewMessage(ctx.Message(), WithDuration(0, bot))
|
||||
NewMessage(m, 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
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), str.MarkdownEscape(toUserStrMention)))
|
||||
return
|
||||
}
|
||||
|
||||
if user.ID == toUserDb.ID {
|
||||
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "sendYourselfMessage"))
|
||||
return ctx, errors.Create(errors.SelfPaymentError)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "sendYourselfMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
// entire text of the inline object
|
||||
@@ -177,7 +173,7 @@ func (bot *TipBot) sendHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
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", ctx.Message().Sender.ID, amount, RandStringRunes(5))
|
||||
id := fmt.Sprintf("send-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
|
||||
sendData := &SendData{
|
||||
From: user,
|
||||
Base: storage.New(storage.ID(id)),
|
||||
@@ -193,10 +189,10 @@ func (bot *TipBot) sendHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
|
||||
sendDataJson, err := json.Marshal(sendData)
|
||||
if err != nil {
|
||||
NewMessage(ctx.Message(), WithDuration(0, bot))
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
log.Printf("[/send] Error: %s\n", err.Error())
|
||||
bot.trySendMessage(ctx.Message().Sender, fmt.Sprint(Translate(ctx, "errorTryLaterMessage")))
|
||||
return ctx, err
|
||||
bot.trySendMessage(m.Sender, fmt.Sprint(Translate(ctx, "errorTryLaterMessage")))
|
||||
return
|
||||
}
|
||||
// save the send data to the Database
|
||||
// log.Debug(sendData)
|
||||
@@ -211,73 +207,32 @@ func (bot *TipBot) sendHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
sendButton,
|
||||
cancelButton),
|
||||
)
|
||||
if ctx.Message().Private() {
|
||||
bot.trySendMessage(ctx.Chat(), confirmText, sendConfirmationMenu)
|
||||
if m.Private() {
|
||||
bot.trySendMessage(m.Chat, confirmText, sendConfirmationMenu)
|
||||
} else {
|
||||
bot.tryReplyMessage(ctx.Message(), confirmText, sendConfirmationMenu)
|
||||
bot.tryReplyMessage(m, 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 intercept.Context) (intercept.Context, error) {
|
||||
tx := &SendData{Base: storage.New(storage.ID(ctx.Data()))}
|
||||
func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
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.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
sendData := sn.(*SendData)
|
||||
// onnly the correct user can press
|
||||
if sendData.From.Telegram.ID != ctx.Callback().Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
if sendData.From.Telegram.ID != c.Sender.ID {
|
||||
return
|
||||
}
|
||||
if !sendData.Active {
|
||||
log.Errorf("[acceptSendHandler] send not active anymore")
|
||||
// bot.tryDeleteMessage(c.Message)
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
return
|
||||
}
|
||||
defer sendData.Set(sendData, bot.Bunt)
|
||||
|
||||
@@ -299,15 +254,15 @@ func (bot *TipBot) confirmSendHandler(ctx intercept.Context) (intercept.Context,
|
||||
to, err := GetLnbitsUser(&tb.User{ID: toId, Username: toUserStrWithoutAt}, *bot)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
bot.tryDeleteMessage(ctx.Callback().Message)
|
||||
return ctx, err
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
}
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
|
||||
transactionMemo := fmt.Sprintf("💸 Send from %s to %s.", fromUserStr, toUserStr)
|
||||
transactionMemo := fmt.Sprintf("Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
t := NewTransaction(bot, from, to, amount, TransactionType("send"))
|
||||
t.Memo = transactionMemo
|
||||
|
||||
@@ -316,8 +271,8 @@ func (bot *TipBot) confirmSendHandler(ctx intercept.Context) (intercept.Context,
|
||||
// bot.trySendMessage(c.Sender, sendErrorMessage)
|
||||
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
bot.tryEditMessage(ctx.Callback().Message, i18n.Translate(sendData.LanguageCode, "sendErrorMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(sendData.LanguageCode, "sendErrorMessage"), &tb.ReplyMarkup{})
|
||||
return
|
||||
}
|
||||
sendData.Inactivate(sendData, bot.Bunt)
|
||||
|
||||
@@ -326,29 +281,25 @@ func (bot *TipBot) confirmSendHandler(ctx intercept.Context) (intercept.Context,
|
||||
// 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 ctx.Callback().Message.Private() {
|
||||
if c.Message.Private() {
|
||||
// if the command was invoked in private chat
|
||||
// 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))
|
||||
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd), &tb.ReplyMarkup{})
|
||||
} else {
|
||||
// if the command was invoked in group chat
|
||||
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{})
|
||||
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{})
|
||||
}
|
||||
// send memo if it was present
|
||||
if len(sendMemo) > 0 {
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(sendMemo)))
|
||||
}
|
||||
|
||||
return ctx, nil
|
||||
return
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot *TipBot) cancelSendHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
// reset state immediately
|
||||
c := ctx.Callback()
|
||||
user := LoadUser(ctx)
|
||||
ResetUserState(user, bot)
|
||||
tx := &SendData{Base: storage.New(storage.ID(c.Data))}
|
||||
@@ -357,17 +308,15 @@ func (bot *TipBot) cancelSendHandler(ctx intercept.Context) (intercept.Context,
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
sendData := sn.(*SendData)
|
||||
// onnly the correct user can press
|
||||
if sendData.From.Telegram.ID != c.Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
return
|
||||
}
|
||||
// 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"))
|
||||
// remove buttons from confirmation message
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(sendData.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
|
||||
sendData.Inactivate(sendData, bot.Bunt)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
+181
-288
File diff suppressed because it is too large
Load Diff
@@ -1,19 +1,22 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
"time"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot TipBot) shopsMainMenu(ctx intercept.Context, shops *Shops) *tb.ReplyMarkup {
|
||||
func (bot TipBot) shopsMainMenu(ctx context.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)
|
||||
@@ -32,7 +35,7 @@ func (bot TipBot) shopsMainMenu(ctx intercept.Context, shops *Shops) *tb.ReplyMa
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
func (bot TipBot) shopsSettingsMenu(ctx intercept.Context, shops *Shops) *tb.ReplyMarkup {
|
||||
func (bot TipBot) shopsSettingsMenu(ctx context.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)
|
||||
@@ -63,11 +66,11 @@ func (bot TipBot) shopsSettingsMenu(ctx intercept.Context, shops *Shops) *tb.Rep
|
||||
}
|
||||
|
||||
// shopItemSettingsMenu builds the buttons of the item settings
|
||||
func (bot TipBot) shopItemSettingsMenu(ctx intercept.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
|
||||
func (bot TipBot) shopItemSettingsMenu(ctx context.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)
|
||||
shopItemAddFileButton = shopKeyboard.Data("💾 Add file", "shop_itemaddfile", item.ID)
|
||||
shopItemSettingsBackButton = shopKeyboard.Data("⬅️ Back", "shop_itemsettingsback", item.ID)
|
||||
user := LoadUser(ctx)
|
||||
buttons := []tb.Row{}
|
||||
@@ -83,7 +86,7 @@ func (bot TipBot) shopItemSettingsMenu(ctx intercept.Context, shop *Shop, item *
|
||||
}
|
||||
|
||||
// shopItemConfirmBuyMenu builds the buttons to confirm a purchase
|
||||
func (bot TipBot) shopItemConfirmBuyMenu(ctx intercept.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
|
||||
func (bot TipBot) shopItemConfirmBuyMenu(ctx context.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{}
|
||||
@@ -96,7 +99,7 @@ func (bot TipBot) shopItemConfirmBuyMenu(ctx intercept.Context, shop *Shop, item
|
||||
}
|
||||
|
||||
// shopMenu builds the buttons in the item browser
|
||||
func (bot TipBot) shopMenu(ctx intercept.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
|
||||
func (bot TipBot) shopMenu(ctx context.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
|
||||
user := LoadUser(ctx)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
@@ -149,7 +152,7 @@ func (bot *TipBot) makseShopSelectionButtons(shops []*Shop, uniqueString string)
|
||||
// -------------- 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) {
|
||||
func (bot *TipBot) getUserShopview(ctx context.Context, user *lnbits.User) (shopView ShopView, err error) {
|
||||
sv, err := bot.Cache.Get(fmt.Sprintf("shopview-%d", user.Telegram.ID))
|
||||
if err != nil {
|
||||
return
|
||||
@@ -157,35 +160,38 @@ func (bot *TipBot) getUserShopview(ctx intercept.Context, user *lnbits.User) (sh
|
||||
shopView = sv.(ShopView)
|
||||
return
|
||||
}
|
||||
func (bot *TipBot) shopViewDeleteAllStatusMsgs(ctx intercept.Context, user *lnbits.User) (shopView ShopView, err error) {
|
||||
func (bot *TipBot) shopViewDeleteAllStatusMsgs(ctx context.Context, user *lnbits.User, start int) (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)
|
||||
|
||||
statusMessages := shopView.StatusMessages
|
||||
// delete all status messages from cache
|
||||
shopView.StatusMessages = append([]*tb.Message{}, statusMessages[0:start]...)
|
||||
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
|
||||
|
||||
deleteStatusMessages(start, statusMessages, bot)
|
||||
mutex.Unlock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
|
||||
return
|
||||
}
|
||||
|
||||
func deleteStatusMessages(messages []*tb.Message, bot *TipBot) {
|
||||
func deleteStatusMessages(start int, messages []*tb.Message, bot *TipBot) {
|
||||
// delete all status messages from telegram
|
||||
for _, msg := range messages {
|
||||
for _, msg := range messages[start:] {
|
||||
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) {
|
||||
func (bot *TipBot) sendStatusMessage(ctx context.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
|
||||
@@ -193,12 +199,13 @@ func (bot *TipBot) sendStatusMessage(ctx intercept.Context, to tb.Recipient, wha
|
||||
statusMsg := bot.trySendMessage(to, what, options...)
|
||||
shopView.StatusMessages = append(shopView.StatusMessages, statusMsg)
|
||||
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
|
||||
mutex.Unlock(id)
|
||||
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) {
|
||||
func (bot *TipBot) sendStatusMessageAndDelete(ctx context.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...)
|
||||
@@ -206,7 +213,7 @@ func (bot *TipBot) sendStatusMessageAndDelete(ctx intercept.Context, to tb.Recip
|
||||
ticker := runtime.GetTicker(id, runtime.WithDuration(5*time.Second))
|
||||
if !ticker.Started {
|
||||
ticker.Do(func() {
|
||||
bot.shopViewDeleteAllStatusMsgs(ctx, user)
|
||||
bot.shopViewDeleteAllStatusMsgs(ctx, user, 1)
|
||||
// removing ticker asap done
|
||||
runtime.RemoveTicker(id)
|
||||
})
|
||||
@@ -219,10 +226,11 @@ func (bot *TipBot) sendStatusMessageAndDelete(ctx intercept.Context, to tb.Recip
|
||||
// --------------- 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) {
|
||||
func (bot *TipBot) initUserShops(ctx context.Context, user *lnbits.User) (*Shops, error) {
|
||||
id := fmt.Sprintf("shops-%d", user.Telegram.ID)
|
||||
shops := &Shops{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
ID: id,
|
||||
Owner: user,
|
||||
Shops: []string{},
|
||||
MaxShops: MAX_SHOPS,
|
||||
@@ -232,8 +240,10 @@ func (bot *TipBot) initUserShops(ctx intercept.Context, user *lnbits.User) (*Sho
|
||||
}
|
||||
|
||||
// getUserShops returns the Shops for the user
|
||||
func (bot *TipBot) getUserShops(ctx intercept.Context, user *lnbits.User) (*Shops, error) {
|
||||
func (bot *TipBot) getUserShops(ctx context.Context, user *lnbits.User) (*Shops, error) {
|
||||
tx := &Shops{Base: storage.New(storage.ID(fmt.Sprintf("shops-%d", user.Telegram.ID)))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.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)
|
||||
@@ -244,7 +254,7 @@ func (bot *TipBot) getUserShops(ctx intercept.Context, user *lnbits.User) (*Shop
|
||||
}
|
||||
|
||||
// addUserShop adds a new Shop to the Shops of a user
|
||||
func (bot *TipBot) addUserShop(ctx intercept.Context, user *lnbits.User) (*Shop, error) {
|
||||
func (bot *TipBot) addUserShop(ctx context.Context, user *lnbits.User) (*Shop, error) {
|
||||
shops, err := bot.getUserShops(ctx, user)
|
||||
if err != nil {
|
||||
return &Shop{}, err
|
||||
@@ -252,6 +262,7 @@ func (bot *TipBot) addUserShop(ctx intercept.Context, user *lnbits.User) (*Shop,
|
||||
shopId := fmt.Sprintf("shop-%s", RandStringRunes(10))
|
||||
shop := &Shop{
|
||||
Base: storage.New(storage.ID(shopId)),
|
||||
ID: shopId,
|
||||
Title: fmt.Sprintf("Shop %d (%s)", len(shops.Shops)+1, shopId),
|
||||
Owner: user,
|
||||
Type: "photo",
|
||||
@@ -266,9 +277,11 @@ func (bot *TipBot) addUserShop(ctx intercept.Context, user *lnbits.User) (*Shop,
|
||||
return shop, nil
|
||||
}
|
||||
|
||||
// getShop returns the Shop of a given ID
|
||||
func (bot *TipBot) getShop(ctx intercept.Context, shopId string) (*Shop, error) {
|
||||
// getShop returns the Shop for the given ID
|
||||
func (bot *TipBot) getShop(ctx context.Context, shopId string) (*Shop, error) {
|
||||
tx := &Shop{Base: storage.New(storage.ID(shopId))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
sn, err := tx.Get(tx, bot.ShopBunt)
|
||||
if err != nil {
|
||||
|
||||
+17
-26
@@ -2,62 +2,57 @@ package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"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/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func (bot TipBot) startHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
if !ctx.Message().Private() {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
func (bot TipBot) startHandler(ctx context.Context, m *tb.Message) {
|
||||
if !m.Private() {
|
||||
return
|
||||
}
|
||||
// ATTENTION: DO NOT CALL ANY HANDLER BEFORE THE WALLET IS CREATED
|
||||
// WILL RESULT IN AN ENDLESS LOOP OTHERWISE
|
||||
// bot.helpHandler(m)
|
||||
log.Printf("[⭐️ /start] New user: %s (%d)\n", GetUserStr(ctx.Sender()), ctx.Sender().ID)
|
||||
walletCreationMsg := bot.trySendMessageEditable(ctx.Sender(), Translate(ctx, "startSettingWalletMessage"))
|
||||
user, err := bot.initWallet(ctx.Sender())
|
||||
log.Printf("[⭐️ /start] New user: %s (%d)\n", GetUserStr(m.Sender), m.Sender.ID)
|
||||
walletCreationMsg, err := bot.Telegram.Send(m.Sender, Translate(ctx, "startSettingWalletMessage"))
|
||||
user, err := bot.initWallet(m.Sender)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[startHandler] Error with initWallet: %s", err.Error()))
|
||||
bot.tryEditMessage(walletCreationMsg, Translate(ctx, "startWalletErrorMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
bot.tryDeleteMessage(walletCreationMsg)
|
||||
ctx.Context = context.WithValue(ctx, "user", user)
|
||||
bot.helpHandler(ctx)
|
||||
bot.trySendMessage(ctx.Sender(), Translate(ctx, "startWalletReadyMessage"))
|
||||
bot.balanceHandler(ctx)
|
||||
ctx = context.WithValue(ctx, "user", user)
|
||||
bot.helpHandler(ctx, m)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "startWalletReadyMessage"))
|
||||
bot.balanceHandler(ctx, m)
|
||||
|
||||
// send the user a warning about the fact that they need to set a username
|
||||
if len(ctx.Sender().Username) == 0 {
|
||||
bot.trySendMessage(ctx.Sender(), Translate(ctx, "startNoUsernameMessage"), tb.NoPreview)
|
||||
if len(m.Sender.Username) == 0 {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "startNoUsernameMessage"), tb.NoPreview)
|
||||
}
|
||||
return ctx, nil
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
|
||||
user, err := GetUser(tguser, bot)
|
||||
if stderrors.Is(err, gorm.ErrRecordNotFound) {
|
||||
if errors.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 {
|
||||
@@ -104,11 +99,7 @@ func (bot TipBot) createWallet(user *lnbits.User) error {
|
||||
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)
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type StateCallbackMessage map[lnbits.UserStateKey]func(ctx intercept.Context) (intercept.Context, error)
|
||||
type StateCallbackMessage map[lnbits.UserStateKey]func(ctx context.Context, m *tb.Message)
|
||||
|
||||
var stateCallbackMessage StateCallbackMessage
|
||||
|
||||
|
||||
@@ -8,11 +8,35 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/rate"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
// appendMainMenu will check if to (recipient) ID is from private or group chat.
|
||||
// this function will only add a keyboard if this is a private chat and no force reply.
|
||||
func appendMainMenu(to int64, options []interface{}) []interface{} {
|
||||
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
|
||||
}
|
||||
|
||||
// getChatIdFromRecipient will parse the recipient to int64
|
||||
func (bot *TipBot) getChatIdFromRecipient(to tb.Recipient) (int64, error) {
|
||||
func getChatIdFromRecipient(to tb.Recipient) (int64, error) {
|
||||
chatId, err := strconv.ParseInt(to.Recipient(), 10, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -23,12 +47,12 @@ func (bot *TipBot) getChatIdFromRecipient(to tb.Recipient) (int64, error) {
|
||||
func (bot TipBot) tryForwardMessage(to tb.Recipient, what tb.Editable, options ...interface{}) (msg *tb.Message) {
|
||||
rate.CheckLimit(to)
|
||||
// ChatId is used for the keyboard
|
||||
chatId, err := bot.getChatIdFromRecipient(to)
|
||||
chatId, err := 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)...)
|
||||
msg, err = bot.Telegram.Forward(to, what, appendMainMenu(chatId, options)...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
@@ -37,22 +61,12 @@ func (bot TipBot) tryForwardMessage(to tb.Recipient, what tb.Editable, options .
|
||||
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)
|
||||
chatId, err := 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...)
|
||||
msg, err = bot.Telegram.Send(to, what, appendMainMenu(chatId, options)...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
@@ -61,28 +75,23 @@ func (bot TipBot) trySendMessageEditable(to tb.Recipient, what interface{}, opti
|
||||
|
||||
func (bot TipBot) tryReplyMessage(to *tb.Message, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
rate.CheckLimit(to)
|
||||
msg, err := bot.Telegram.Reply(to, what, bot.appendMainMenu(to.Chat.ID, to, options)...)
|
||||
msg, err := bot.Telegram.Reply(to, what, appendMainMenu(to.Chat.ID, options)...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
rate.CheckLimit(to)
|
||||
var err error
|
||||
_, chatId := to.MessageSig()
|
||||
log.Tracef("[tryEditMessage] sig: %s, chatId: %d", sig, chatId)
|
||||
msg, err = bot.Telegram.Edit(to, what, options...)
|
||||
msg, err = bot.Telegram.Edit(to, what, appendMainMenu(chatId, options)...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
func (bot TipBot) tryDeleteMessage(msg tb.Editable) {
|
||||
@@ -137,48 +146,3 @@ func isAdminAndCanDelete(members []tb.ChatMember, me *tb.User) bool {
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
+20
-31
@@ -4,52 +4,42 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot *TipBot) anyTextHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
func (bot *TipBot) anyTextHandler(ctx context.Context, m *tb.Message) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
return
|
||||
}
|
||||
|
||||
// check if user is in Database, if not, initialize wallet
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil || !user.Initialized {
|
||||
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)
|
||||
bot.startHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
// could be an invoice
|
||||
anyText := strings.ToLower(m.Text)
|
||||
if lightning.IsInvoice(anyText) {
|
||||
m.Text = "/pay " + anyText
|
||||
return bot.payHandler(ctx)
|
||||
bot.payHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
if lightning.IsLnurl(anyText) {
|
||||
m.Text = "/lnurl " + anyText
|
||||
return bot.lnurlHandler(ctx)
|
||||
bot.lnurlHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
if c := stateCallbackMessage[user.StateKey]; c != nil {
|
||||
return c(ctx)
|
||||
c(ctx, m)
|
||||
//ResetUserState(user, bot)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
type EnterUserStateData struct {
|
||||
@@ -85,21 +75,20 @@ func (bot *TipBot) askForUser(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 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()
|
||||
// any other handler that relies on this, needs to load the resulting amount from the database
|
||||
func (bot *TipBot) enterUserHandler(ctx context.Context, m *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return // errors.New("user has no wallet"), 0
|
||||
}
|
||||
|
||||
if !(user.StateKey == lnbits.UserEnterUser) {
|
||||
ResetUserState(user, bot)
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
return // errors.New("user state does not match"), 0
|
||||
}
|
||||
if len(m.Text) < 4 || strings.HasPrefix(m.Text, "/") || m.Text == SendMenuCommandEnter {
|
||||
if len(m.Text) < 4 || strings.HasPrefix(m.Text, "/") {
|
||||
ResetUserState(user, bot)
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
return
|
||||
}
|
||||
|
||||
var EnterUserStateData EnterUserStateData
|
||||
@@ -107,7 +96,7 @@ func (bot *TipBot) enterUserHandler(ctx intercept.Context) (intercept.Context, e
|
||||
if err != nil {
|
||||
log.Errorf("[EnterUserHandler] %s", err.Error())
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
userstr := m.Text
|
||||
@@ -117,10 +106,10 @@ func (bot *TipBot) enterUserHandler(ctx intercept.Context) (intercept.Context, e
|
||||
switch EnterUserStateData.Type {
|
||||
case "CreateSendState":
|
||||
m.Text = fmt.Sprintf("/send %s", userstr)
|
||||
return bot.sendHandler(ctx)
|
||||
bot.sendHandler(ctx, m)
|
||||
return
|
||||
default:
|
||||
ResetUserState(user, bot)
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
return
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
+19
-19
@@ -6,15 +6,12 @@ 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/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func helpTipUsage(ctx context.Context, errormsg string) string {
|
||||
@@ -33,13 +30,12 @@ func TipCheckSyntax(ctx context.Context, m *tb.Message) (bool, string) {
|
||||
return true, ""
|
||||
}
|
||||
|
||||
func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx)
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, fmt.Errorf("user has no wallet")
|
||||
return
|
||||
}
|
||||
|
||||
// only if message is a reply
|
||||
@@ -47,13 +43,13 @@ func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
bot.tryDeleteMessage(m)
|
||||
bot.trySendMessage(m.Sender, helpTipUsage(ctx, Translate(ctx, "tipDidYouReplyMessage")))
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "tipInviteGroupMessage"))
|
||||
return ctx, errors.Create(errors.NoReplyMessageError)
|
||||
return
|
||||
}
|
||||
|
||||
if ok, err := TipCheckSyntax(ctx, m); !ok {
|
||||
bot.trySendMessage(m.Sender, helpTipUsage(ctx, err))
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
return
|
||||
}
|
||||
|
||||
// get tip amount
|
||||
@@ -64,12 +60,12 @@ func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpTipUsage(ctx, Translate(ctx, "tipValidAmountMessage")))
|
||||
log.Warnln(errmsg)
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
return
|
||||
}
|
||||
|
||||
err = bot.parseCmdDonHandler(ctx)
|
||||
err = bot.parseCmdDonHandler(ctx, m)
|
||||
if err == nil {
|
||||
return ctx, fmt.Errorf("invalid parseCmdDonHandler")
|
||||
return
|
||||
}
|
||||
// TIP COMMAND IS VALID
|
||||
from := LoadUser(ctx)
|
||||
@@ -78,7 +74,7 @@ func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "tipYourselfMessage"))
|
||||
return ctx, fmt.Errorf("cannot tip yourself")
|
||||
return
|
||||
}
|
||||
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
@@ -92,7 +88,7 @@ func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[/tip] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, fmt.Errorf("could not create wallet for %s", toUserStr)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,7 +103,7 @@ func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
}
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("🏅 Tip from %s to %s.", fromUserStr, toUserStr)
|
||||
transactionMemo := fmt.Sprintf("Tip from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
t := NewTransaction(bot, from, to, amount, TransactionType("tip"), TransactionChat(m.Chat))
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
@@ -116,7 +112,7 @@ func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf("%s %s", Translate(ctx, "tipErrorMessage"), err))
|
||||
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err.Error())
|
||||
log.Warnln(errMsg)
|
||||
return ctx, fmt.Errorf("could not create wallet for %s", toUserStr)
|
||||
return
|
||||
}
|
||||
|
||||
// update tooltip if necessary
|
||||
@@ -125,7 +121,11 @@ func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
log.Infof("[💸 tip] Tip from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
|
||||
// notify users
|
||||
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "tipSentMessage"), amount, toUserStrMd))
|
||||
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "tipSentMessage"), amount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[/tip] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
|
||||
// forward tipped message to user once
|
||||
if !messageHasTip {
|
||||
@@ -138,5 +138,5 @@ func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
}
|
||||
// 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
|
||||
return
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type Transaction struct {
|
||||
@@ -76,7 +76,7 @@ func (t *Transaction) Send() (success bool, err error) {
|
||||
}
|
||||
|
||||
// save transaction to db
|
||||
tx := t.Bot.DB.Transactions.Save(t)
|
||||
tx := t.Bot.logger.Save(t)
|
||||
if tx.Error != nil {
|
||||
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
@@ -91,19 +91,19 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
|
||||
t.FromWallet = from.Wallet.ID
|
||||
t.FromLNbitsID = from.ID
|
||||
|
||||
// check if fromUser has balance
|
||||
balance, err := bot.GetUserBalance(from)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return false, err
|
||||
}
|
||||
// check if fromUser has balance
|
||||
if balance < amount {
|
||||
errmsg := fmt.Sprintf("balance too low.")
|
||||
log.Warnf("Balance of user %s too low", fromUserStr)
|
||||
return false, fmt.Errorf(errmsg)
|
||||
}
|
||||
// // check if fromUser has balance
|
||||
// balance, err := bot.GetUserBalance(from)
|
||||
// if err != nil {
|
||||
// errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
// log.Errorln(errmsg)
|
||||
// return false, err
|
||||
// }
|
||||
// // check if fromUser has balance
|
||||
// if balance < amount {
|
||||
// errmsg := fmt.Sprintf("balance too low.")
|
||||
// log.Warnf("Balance of user %s too low", fromUserStr)
|
||||
// return false, fmt.Errorf(errmsg)
|
||||
// }
|
||||
|
||||
t.ToWallet = to.ID
|
||||
t.ToLNbitsID = to.ID
|
||||
@@ -128,20 +128,5 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
|
||||
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,173 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
type TransactionsList struct {
|
||||
ID string `json:"id"`
|
||||
User *lnbits.User `json:"from"`
|
||||
Payments lnbits.Payments `json:"payments"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
CurrentPage int `json:"currentpage"`
|
||||
MaxPages int `json:"maxpages"`
|
||||
TxPerPage int `json:"txperpage"`
|
||||
}
|
||||
|
||||
func (txlist *TransactionsList) printTransactions(ctx intercept.Context) string {
|
||||
txstr := ""
|
||||
// for _, p := range payments {
|
||||
payments := txlist.Payments
|
||||
pagenr := txlist.CurrentPage
|
||||
tx_per_page := txlist.TxPerPage
|
||||
if pagenr > (len(payments)+1)/tx_per_page {
|
||||
pagenr = 0
|
||||
}
|
||||
if len(payments) < tx_per_page {
|
||||
tx_per_page = len(payments)
|
||||
}
|
||||
start := pagenr * (tx_per_page - 1)
|
||||
end := start + tx_per_page
|
||||
if end >= len(payments) {
|
||||
end = len(payments) - 1
|
||||
}
|
||||
for i := start; i <= end; i++ {
|
||||
p := payments[i]
|
||||
if p.Pending {
|
||||
txstr += "🔄"
|
||||
} else {
|
||||
if p.Amount < 0 {
|
||||
txstr += "🔴"
|
||||
} else {
|
||||
txstr += "🟢"
|
||||
}
|
||||
}
|
||||
timestr := time.Unix(int64(p.Time), 0).UTC().Format("2 Jan 06 15:04")
|
||||
txstr += fmt.Sprintf("` %s`", timestr)
|
||||
txstr += fmt.Sprintf("` %+d sat`", p.Amount/1000)
|
||||
if p.Fee > 0 {
|
||||
fee := p.Fee
|
||||
if fee < 1000 {
|
||||
fee = 1000
|
||||
}
|
||||
txstr += fmt.Sprintf(" _(fee: %d sat)_", fee/1000)
|
||||
}
|
||||
memo := p.Memo
|
||||
memo_maxlen := 50
|
||||
if len(memo) > memo_maxlen {
|
||||
memo = memo[:memo_maxlen] + "..."
|
||||
}
|
||||
if len(memo) > 0 {
|
||||
txstr += fmt.Sprintf("\n✉️ %s", str.MarkdownEscape(memo))
|
||||
}
|
||||
txstr += "\n"
|
||||
}
|
||||
txstr += fmt.Sprintf("\nShowing %d transactions. Page %d of %d.", len(payments), txlist.CurrentPage+1, txlist.MaxPages)
|
||||
return txstr
|
||||
}
|
||||
|
||||
var (
|
||||
transactionsMeno = &tb.ReplyMarkup{ResizeKeyboard: true}
|
||||
btnLeftTransactionsButton = inlineTipjarMenu.Data("◀️", "left_transactions")
|
||||
btnRightTransactionsButton = inlineTipjarMenu.Data("▶️", "right_transactions")
|
||||
)
|
||||
|
||||
func (bot *TipBot) makeTransactionsKeyboard(ctx intercept.Context, txlist TransactionsList) *tb.ReplyMarkup {
|
||||
leftTransactionsButton := transactionsMeno.Data("←", "left_transactions", txlist.ID)
|
||||
rightTransactionsButton := transactionsMeno.Data("→", "right_transactions", txlist.ID)
|
||||
|
||||
if txlist.CurrentPage == 0 {
|
||||
transactionsMeno.Inline(
|
||||
transactionsMeno.Row(
|
||||
leftTransactionsButton),
|
||||
)
|
||||
} else if txlist.CurrentPage == txlist.MaxPages-1 {
|
||||
transactionsMeno.Inline(
|
||||
transactionsMeno.Row(
|
||||
rightTransactionsButton),
|
||||
)
|
||||
} else {
|
||||
transactionsMeno.Inline(
|
||||
transactionsMeno.Row(
|
||||
leftTransactionsButton,
|
||||
rightTransactionsButton),
|
||||
)
|
||||
}
|
||||
return transactionsMeno
|
||||
}
|
||||
|
||||
func (bot *TipBot) transactionsHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
user := LoadUser(ctx)
|
||||
payments, err := bot.Client.Payments(*user.Wallet)
|
||||
if err != nil {
|
||||
log.Errorf("[transactions] Error: %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
tx_per_page := 10
|
||||
transactionsList := TransactionsList{
|
||||
ID: fmt.Sprintf("txlist:%d:%s", user.Telegram.ID, RandStringRunes(5)),
|
||||
User: user,
|
||||
Payments: payments,
|
||||
LanguageCode: ctx.Value("userLanguageCode").(string),
|
||||
CurrentPage: 0,
|
||||
TxPerPage: tx_per_page,
|
||||
MaxPages: (len(payments)+1)/tx_per_page + 1,
|
||||
}
|
||||
bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), transactionsList, &store.Options{Expiration: 1 * time.Minute})
|
||||
txstr := transactionsList.printTransactions(ctx)
|
||||
bot.trySendMessage(m.Sender, txstr, bot.makeTransactionsKeyboard(ctx, transactionsList))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) transactionsScrollLeftHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
user := LoadUser(ctx)
|
||||
transactionsListInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
|
||||
if err != nil {
|
||||
log.Info("Transactions not in cache anymore")
|
||||
return ctx, err
|
||||
}
|
||||
transactionsList := transactionsListInterface.(TransactionsList)
|
||||
|
||||
if c.Sender.ID == transactionsList.User.Telegram.ID {
|
||||
if transactionsList.CurrentPage < transactionsList.MaxPages-1 {
|
||||
transactionsList.CurrentPage++
|
||||
} else {
|
||||
return ctx, err
|
||||
}
|
||||
bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), transactionsList, &store.Options{Expiration: 1 * time.Minute})
|
||||
bot.tryEditMessage(c.Message, transactionsList.printTransactions(ctx), bot.makeTransactionsKeyboard(ctx, transactionsList))
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) transactionsScrollRightHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
c := ctx.Callback()
|
||||
user := LoadUser(ctx)
|
||||
transactionsListInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
|
||||
if err != nil {
|
||||
log.Info("Transactions not in cache anymore")
|
||||
return ctx, err
|
||||
}
|
||||
transactionsList := transactionsListInterface.(TransactionsList)
|
||||
|
||||
if c.Sender.ID == transactionsList.User.Telegram.ID {
|
||||
if transactionsList.CurrentPage > 0 {
|
||||
transactionsList.CurrentPage--
|
||||
} else {
|
||||
return ctx, nil
|
||||
}
|
||||
bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), transactionsList, &store.Options{Expiration: 1 * time.Minute})
|
||||
bot.tryEditMessage(c.Message, transactionsList.printTransactions(ctx), bot.makeTransactionsKeyboard(ctx, transactionsList))
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
@@ -3,14 +3,13 @@ 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/lightningtipbot/telebot.v3"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -84,22 +83,18 @@ func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
|
||||
}
|
||||
// msat to sat
|
||||
amount = int64(wallet.Balance) / 1000
|
||||
log.Debugf("[GetUserBalance] %s's balance: %d sat\n", GetUserStr(user.Telegram), amount)
|
||||
log.Infof("[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: 1 * time.Hour},
|
||||
&store.Options{Expiration: 30 * time.Second},
|
||||
)
|
||||
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)
|
||||
@@ -109,7 +104,6 @@ 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
|
||||
@@ -125,16 +119,3 @@ 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
|
||||
}
|
||||
|
||||
@@ -4,27 +4,17 @@ import (
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
|
||||
"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/lnurl"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/price"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
log "github.com/sirupsen/logrus"
|
||||
_ "net/http/pprof"
|
||||
)
|
||||
|
||||
// setLogger will initialize the log format
|
||||
func setLogger() {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
log.SetLevel(log.TraceLevel)
|
||||
customFormatter := new(log.TextFormatter)
|
||||
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
|
||||
customFormatter.FullTimestamp = true
|
||||
@@ -34,46 +24,14 @@ func setLogger() {
|
||||
func main() {
|
||||
// set logger
|
||||
setLogger()
|
||||
|
||||
go http.ListenAndServe("0.0.0.0:6060", nil)
|
||||
defer withRecovery()
|
||||
price.NewPriceWatcher().Start()
|
||||
bot := telegram.NewBot()
|
||||
startApiServer(&bot)
|
||||
webhook.NewServer(&bot)
|
||||
lnurl.NewServer(&bot)
|
||||
price.NewPriceWatcher().Start()
|
||||
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)
|
||||
|
||||
// append lndhub ctx functions
|
||||
hub := lndhub.New(bot)
|
||||
s.AppendRoute(`/lndhub/ext/{.*}`, hub.Handle)
|
||||
s.AppendRoute(`/lndhub/ext`, hub.Handle)
|
||||
|
||||
// start internal admin server
|
||||
adminService := admin.New(bot)
|
||||
internalAdminServer := api.NewServer("0.0.0.0:6060")
|
||||
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.PathPrefix("/debug/pprof/", http.DefaultServeMux)
|
||||
|
||||
}
|
||||
|
||||
func withRecovery() {
|
||||
if r := recover(); r != nil {
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 282 KiB After Width: | Height: | Size: 22 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 102 KiB |
+3
-13
@@ -118,13 +118,10 @@ advancedMessage = """%s
|
||||
📖 Du kannst Inline Befehle in jedem Chat verwenden, sogar in privaten Nachrichten. Warte eine Sekunde, nachdem du den Befehl eingegeben hast und *klicke* auf das Ergebnis, statt Enter einzugeben.
|
||||
|
||||
⚙️ *Fortgeschrittene Befehle*
|
||||
*/transactions* 📊 Liste der Transaktionen
|
||||
*/link* 🔗 Verbinde dein Wallet mit [BlueWallet](https://bluewallet.io/) oder [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl empfangen oder senden: `/lnurl` oder `/lnurl <lnurl>`
|
||||
*/lnurl* ⚡️ Lnurl empfangen oder senden: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Erzeuge einen Zapfhahn: `/faucet <gesamt> <pro_user>`
|
||||
*/tipjar* 🍯 Erzeuge eine Spendendose: `/tipjar <gesamt> <pro_user>`
|
||||
*/group* 🎟 Tickets für Gruppenchats: `/group add <meine_gruppe> [<ticket_preis>]`
|
||||
*/shop* 🛍 Durchsuche shops: `/shop` oder `/shop <user/shop_id>`"""
|
||||
*/tipjar* 🍯 Erzeuge eine Spendendose: `/tipjar <gesamt> <pro_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """⌨️ Gebe einen Betrag zwischen %d und %d sat ein."""
|
||||
@@ -240,13 +237,6 @@ 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"""
|
||||
@@ -272,7 +262,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 %s's Zapfhahn zu zapfen.
|
||||
inlineFaucetMessage = """Drücke ✅ um %d sat aus diesem Zapfhahn zu zapfen.
|
||||
|
||||
🚰 Verbleibend: %d/%d sat (%d/%d gezapft)
|
||||
%s"""
|
||||
|
||||
+7
-52
@@ -82,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._
|
||||
@@ -121,13 +121,10 @@ advancedMessage = """%s
|
||||
📖 You can use inline commands in every chat, even in private conversations. Wait a second after entering an inline command and *click* the result, don't press enter.
|
||||
|
||||
⚙️ *Advanced commands*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl receive or pay: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Create a faucet: `/faucet <capacity> <per_user>`
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Enter an amount between %d and %d sat."""
|
||||
@@ -192,17 +189,16 @@ 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 to a Lightning address."""
|
||||
invalidInvoiceHelpMessage = """Did you enter a valid Lightning invoice? Try /send if you want to send to a Telegram user or 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. Reserve at least 1% for fees."""
|
||||
feeReserveMessage = """⚠️ Sending your entire balance might fail because of network fees. If it fails, try sending a bit less."""
|
||||
invoicePaymentFailedMessage = """🚫 Payment failed: %s"""
|
||||
invoiceUndefinedErrorMessage = """Could not pay invoice."""
|
||||
confirmPayInvoiceMessage = """Do you want to send this payment?\n\n💸 Amount: %d sat"""
|
||||
@@ -227,7 +223,7 @@ donateHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 Could not recognize a Lightning invoice or a LNURL. Try to center the QR code, crop the photo, or zoom in."""
|
||||
photoQrNotRecognizedMessage = """🚫 Could not regocognize a Lightning invoice or an LNURL. Try to center the QR code, crop the photo, or zoom in."""
|
||||
photoQrRecognizedMessage = """✅ QR code:
|
||||
`%s`"""
|
||||
|
||||
@@ -245,13 +241,6 @@ 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"""
|
||||
@@ -278,7 +267,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 %s's faucet.
|
||||
inlineFaucetMessage = """Press ✅ to collect %d sat from this faucet.
|
||||
|
||||
🚰 Remaining: %d/%d sat (given to %d/%d users)
|
||||
%s"""
|
||||
@@ -286,12 +275,11 @@ 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 or too low (min 5 sat)."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 Peruser amount not divisor of capacity."""
|
||||
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>`
|
||||
@@ -351,36 +339,3 @@ 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`"""
|
||||
+2
-12
@@ -117,13 +117,10 @@ advancedMessage = """%s
|
||||
📖 Puedes usar comandos _inline_ en todos los chats, incluso en las conversaciones privadas. Espera un segundo después de introducir un comando _inline_ y *haz clic* en el resultado, no pulses enter.
|
||||
|
||||
⚙️ *Comandos avanzados*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Enlaza tu monedero a [ BlueWallet ](https://bluewallet.io/) o [ Zeus ](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl recibir o pagar: `/lnurl` o `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Crear un grifo: `/faucet <capacidad> <por_usuario>`
|
||||
*/tipjar* 🍯 Crear un tipjar: `/tipjar <capacidad> <por_usuario>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
*/tipjar* 🍯 Crear un tipjar: `/tipjar <capacidad> <por_usuario>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Introduce un monto entre %d y %d sat."""
|
||||
@@ -240,13 +237,6 @@ 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"""
|
||||
@@ -272,7 +262,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 de %s.
|
||||
inlineFaucetMessage = """Pulsa ✅ para cobrar %d sat de este grifo.
|
||||
|
||||
🚰 Restante: %d/%d sat (dado a %d/%d usuarios)
|
||||
%s"""
|
||||
|
||||
@@ -117,13 +117,10 @@ advancedMessage = """%s
|
||||
📖 Vous pouvez utiliser ces commandes dans tous les chats et même dans les conversations privées. Attendez une seconde après avoir tapé une commandé puis *click* sur le résultat, n'appuyez pas sur entrée.
|
||||
|
||||
⚙️ *Commandes avancées*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Lier votre wallet à [BlueWallet](https://bluewallet.io/) ou [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl recevoir ou payer: `/lnurl` ou `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Créer un faucet: `/faucet <capacité> <par_utilisateur>`
|
||||
*/tipjar* 🍯 Créer un tipjar: `/tipjar <capacité> <par_utilisateur>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
*/tipjar* 🍯 Créer un tipjar: `/tipjar <capacité> <par_utilisateur>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Choisissez un montant entre %d et %d sat."""
|
||||
@@ -257,7 +254,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 de %s.
|
||||
inlineFaucetMessage = """Appuyez sur ✅ pour collecter %d sat de ce faucet.
|
||||
|
||||
🚰 Restant: %d/%d sat (envoyé à %d/%d utilisateurs)
|
||||
%s"""
|
||||
|
||||
@@ -117,13 +117,10 @@ advancedMessage = """%s
|
||||
📖 Kamu dapat menggunakan sebaris perintah di tiap percakapan, bahkan di percakapan privat. Tunggu sejenak setelah memasukkan sebaris perintah lalu *pencet* hasilnya, jangan tekan enter.
|
||||
|
||||
⚙️ *Perintah lanjutan*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Menghubungkan dompet mu ke [BlueWallet](https://bluewallet.io/) atau [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl menerima atau membayar: `/lnurl` atau `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Membuat sebuah keran `/faucet <kapasitas> <per_pengguna>`
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Masukkan jumlah diantara %d dan %d sat."""
|
||||
@@ -265,7 +262,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 %s.
|
||||
inlineFaucetMessage = """Tekan ✅ untuk mengambil %d sat dari keran ini.
|
||||
|
||||
🚰 Tersisa: %d/%d sat (diberikan kepada %d/%d pengguna)
|
||||
%s"""
|
||||
|
||||
@@ -117,13 +117,10 @@ advancedMessage = """%s
|
||||
📖 Puoi usare i comandi in linea in ogni chat, anche nelle conversazioni private. Attendi un secondo dopo aver inviato un comando in linea e *clicca* sull'azione desiderata, non premere invio.
|
||||
|
||||
⚙️ *Comandi avanzati*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Crea un collegamento al tuo wallet [BlueWallet](https://bluewallet.io/) o [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Ricevi o paga un Lnurl: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Crea una distribuzione: `/faucet <totale> <per_utente>`
|
||||
*/tipjar* 🍯 Crea un tipjar: `/tipjar <totale> <per_utente>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
*/tipjar* 🍯 Crea un tipjar: `/tipjar <totale> <per_utente>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Imposta un ammontare tra %d e %d sat."""
|
||||
@@ -257,7 +254,7 @@ inlineQueryFaucetDescription = """Sintassi: @%s faucet <totale> <per_utente>"""
|
||||
inlineResultFaucetTitle = """🚰 Crea una distribuzione per un totale di %d sat."""
|
||||
inlineResultFaucetDescription = """👉 Clicca qui per creare una distribuzione di fondi in questa chat."""
|
||||
|
||||
inlineFaucetMessage = """Premi ✅ per riscuotere %d sat da questa distribuzione da %s.
|
||||
inlineFaucetMessage = """Premi ✅ per riscuotere %d sat da questa distribuzione.
|
||||
|
||||
🚰 Rimanente: %d/%d sat (distribuiti a %d/%d utenti)
|
||||
%s"""
|
||||
|
||||
@@ -117,13 +117,10 @@ advancedMessage = """%s
|
||||
📖 Je kunt inline commando's in elke chat gebruiken, zelfs in privé gesprekken. Wacht een seconde na het invoeren van een inline commando en *klik* op het resultaat, druk niet op enter.
|
||||
|
||||
⚙️ *Geavanceerde opdrachten*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Koppel uw wallet aan [BlueWallet](https://bluewallet.io/) of [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl ontvangen of betalen: `/lnurl` of `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Maak een kraan: `/faucet <capacity> <per_user>`
|
||||
*/tipjar* 🍯 Maak een tipjar: `/tipjar <capacity> <per_user>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
*/tipjar* 🍯 Maak een tipjar: `/tipjar <capacity> <per_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Voer een bedrag in tussen %d en %d sat."""
|
||||
@@ -265,7 +262,7 @@ inlineQueryFaucetDescription = """Gebruik: @%s faucet <capacity> <per_user>"""
|
||||
inlineResultFaucetTitle = """🚰 Maak een %d sat kraan."""
|
||||
inlineResultFaucetDescription = """👉 Klik hier om een kraan in deze chat te maken.."""
|
||||
|
||||
inlineFaucetMessage = """Druk op ✅ om %d sat te verzamelen van deze kraan van %s.
|
||||
inlineFaucetMessage = """Druk op ✅ om %d sat te verzamelen van deze kraan.
|
||||
|
||||
🚰 Remaining: %d/%d sat (given to %d/%d users)
|
||||
%s"""
|
||||
|
||||
+3
-13
@@ -78,7 +78,7 @@ _Este bot não cobra nenhuma comissão, mas custa Satoshis para funcionar. Se vo
|
||||
*/help* 📖 Ler esta ajuda."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Info*"""
|
||||
infoYourLightningAddress = """Seu Lightning address _(endereço lightning)_ é `%s`."""
|
||||
infoYourLightningAddress = """Seu Lightning Address _(Endereço Lightning)_ é `%s`."""
|
||||
|
||||
basicsMessage = """🧡 *Bitcoin*
|
||||
_Bitcoin é a moeda da Internet. É uma moeda sem permissão, descentralizada, sem proprietários e sem autoridade de controle. Bitcoin é dinheiro sólido, mais rápido, mais seguro e mais inclusivo do que o sistema financeiro fiat._
|
||||
@@ -117,13 +117,10 @@ advancedMessage = """%s
|
||||
📖 Você pode usar comandos _inline_ em todas as conversas, mesmo em conversas privadas. Espere um segundo após inserir um comando _inline_ e *clique* no resultado, não pressione enter.
|
||||
|
||||
⚙️ *Comandos avançados*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Vincule sua carteira a [ BlueWallet ](https://bluewallet.io/) ou [ Zeus ](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Receber ou pagar com lnurl: `/lnurl` o `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Criar uma torneira: `/faucet <capacidade> <por_usuário>`
|
||||
*/tipjar* 🍯 Criar uma tipjar: `/tipjar <capacidade> <por_usuário>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
*/tipjar* 🍯 Criar uma tipjar: `/tipjar <capacidade> <por_usuário>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Insira uma quantia entre %d e %d sat."""
|
||||
@@ -240,13 +237,6 @@ lnurlHelpText = """📖 Opa, isso não funcionou. %s
|
||||
*Uso:* `/lnurl [quantidade] <lnurl>`
|
||||
*Exemplo:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL LOGIN
|
||||
|
||||
confirmLnurlAuthMessager = """Você quer fazer login em %s?"""
|
||||
lnurlSuccessfulLogin = """✅ Login com sucesso."""
|
||||
loginButtonMessage = """✅ Login"""
|
||||
loginCancelledMessage = """🚫 Login cancelado."""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """Você quer fazer esse saque?\n💸 Quantia: %d sat"""
|
||||
@@ -272,7 +262,7 @@ inlineQueryFaucetDescription = """Uso: @%s faucet <capacidade> <por_usuário>""
|
||||
inlineResultFaucetTitle = """🚰 Criar uma torneira %d sat."""
|
||||
inlineResultFaucetDescription = """👉 Aperte aqui para criar uma torneira neste chat."""
|
||||
|
||||
inlineFaucetMessage = """Aperte ✅ para coletar %d sat desta torneira de %s.
|
||||
inlineFaucetMessage = """Aperte ✅ para coletar %d sat desta torneira.
|
||||
|
||||
🚰 Restante: %d/%d sat (para %d/%d usuários)
|
||||
%s"""
|
||||
|
||||
@@ -121,13 +121,10 @@ advancedMessage = """%s
|
||||
📖 Вы можете использовать команды в любом чате, даже в личных беседах. Подождите секунду после ввода команды и *щелкните* результат, не нажимайте Enter..
|
||||
|
||||
⚙️ *Продвинутые команды*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
|
||||
*/lnurl* Получить или оплатить через ⚡️Lnurl: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Создать криптораздачу: `/faucet <ёмкость> <на_пользователя>`
|
||||
*/tipjar* 🍯 Создать копилку: `/tipjar <ёмкость> <на_пользователя>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
*/tipjar* 🍯 Создать копилку: `/tipjar <ёмкость> <на_пользователя>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Введите количество между %d и %d sat."""
|
||||
@@ -269,7 +266,7 @@ inlineQueryFaucetDescription = """Использование: @%s faucet <capac
|
||||
inlineResultFaucetTitle = """🚰 Создать %d sat криптораздачу."""
|
||||
inlineResultFaucetDescription = """👉 Нажмите здесь, чтобы создать криптораздачу в этом чате."""
|
||||
|
||||
inlineFaucetMessage = """Нажмите ✅, чтобы забрать %d sat из этой криптораздачи от %s.
|
||||
inlineFaucetMessage = """Нажмите ✅, чтобы забрать %d sat из этой криптораздачи.
|
||||
|
||||
🚰 Осталось: %d/%d sat (отдано %d/%d пользователям)
|
||||
%s"""
|
||||
|
||||
@@ -117,13 +117,10 @@ advancedMessage = """%s
|
||||
📖 İnline komutları her sohbette ve hatta özel mesajlarda kullanabilirsin. Komutu yazdıktan sonra bir saniye bekle ve Enter yazmak yerine sonuca *tıkla*.
|
||||
|
||||
⚙️ *Gelişmiş komutlar*
|
||||
*/transactions* 📊 List transactions
|
||||
*/link* 🔗 Cüzdanını bağla: [BlueWallet](https://bluewallet.io/) veya [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl iste veya gönder: `/lnurl` veya `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Bir fıçı oluştur: `/faucet <toplam> <kullanıcı_başına>`
|
||||
*/tipjar* 🍯 Bir tipjar oluştur: `/tipjar <capacity> <per_user>`
|
||||
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
|
||||
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
|
||||
*/tipjar* 🍯 Bir tipjar oluştur: `/tipjar <capacity> <per_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 %d ve %d sat arasında bir miktar gir."""
|
||||
@@ -257,7 +254,7 @@ inlineQueryFaucetDescription = """Komut: @%s faucet <toplam> <kullanıcı_başı
|
||||
inlineResultFaucetTitle = """🚰 Bir %d sat Fıçı oluştur."""
|
||||
inlineResultFaucetDescription = """👉 Fıçı’yı bu sohbete göndermek için tıkla."""
|
||||
|
||||
inlineFaucetMessage = """✅ butonuna basarak %s'in Fıçıdan %d sat çek.
|
||||
inlineFaucetMessage = """✅ butonuna basarak Fıçıdan %d sat çek.
|
||||
|
||||
🚰 Kalan: %d/%d sat (%d/%d çekildi)
|
||||
%s"""
|
||||
|
||||
Reference in New Issue
Block a user