Compare commits

...
Author SHA1 Message Date
lngohumble 1cd8aa9e17 rename stuff 2021-12-26 02:28:47 +01:00
lngohumble 1a07826513 remove makeQueryFaucet 2021-12-26 02:17:23 +01:00
373ee844da Log oncemap (#233)
* speed up tx lock

* yolo master

* logging

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 00:33:00 +01:00
151ed39b04 add once + singleton click interceptor (#229)
* speed up tx lock

* yolo master

* add once + singleton click interceptor

* yoooo;

* stuff

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 00:23:58 +01:00
24108f6a1f Finish the faucet (#232)
* speed up tx lock

* yolo master

* finish the faucet when inactive

* delete comments

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-25 23:11:31 +01:00
737ab115bd Fix faucet again 1337 (#230)
* speed up tx lock

* yolo master

* fix it

* decrease limit

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-25 14:52:54 +01:00
13957342df Fix faucet again 1337 (#228)
* speed up tx lock

* yolo master

* fix it

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-25 14:43:36 +01:00
fe1a921440 Faucet cool (#227)
* speed up tx lock

* yolo master

* coool

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-25 14:30:25 +01:00
39ff25beca Increase rate limit (#226)
* speed up tx lock

* yolo master

* rate limit

* decrease

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-25 14:14:53 +01:00
ec15f26c13 Increase rate limit (#225)
* speed up tx lock

* yolo master

* rate limit

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-25 14:06:52 +01:00
0218191793 fix button space (#224)
Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-25 13:53:57 +01:00
5065f5af86 Fix button (#223)
* fix options and what

* fix keyboard

Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-25 12:19:28 +01:00
6aca41835d fix options and what (#222)
Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-25 11:39:46 +01:00
6b746447e5 add initial main menu keyboard. (#221)
Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-25 02:50:58 +01:00
ca60b271fd Dont cancel faucet (#220)
* speed up tx lock

* yolo master

* faucet cancel not

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-25 01:42:43 +01:00
gohumbleandGitHub 1b720b498c print faucet link if available (#218) 2021-12-24 18:11:00 +01:00
gohumbleandGitHub 2066470cba send telegram messages async (#219) 2021-12-24 18:10:52 +01:00
73ada1f25b Faucet 1341 (#217)
* speed up tx lock

* yolo master

* faucet fix

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 17:32:01 +01:00
43a77fd1b2 Faucet bla 13340 (#216)
* speed up tx lock

* yolo master

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 17:14:08 +01:00
f968310902 Facuet cancel 1339 (#215)
* speed up tx lock

* cancel better

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 17:10:20 +01:00
32a5a7c264 Faucet cancel 1338 (#214)
* speed up tx lock

* yp

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 17:02:08 +01:00
776de88041 Cancel faucet better (#213)
* speed up tx lock

* base canceled flag

* oops

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 16:54:07 +01:00
192a100f8d Cancel faucet if not empty (#212)
* speed up tx lock

* cancel

* check better

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 16:47:54 +01:00
b796db1979 Cancel faucet if not empty (#211)
* speed up tx lock

* cancel

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 16:39:43 +01:00
gohumbleandGitHub eb07cdf117 disable rl for edit (#210) 2021-12-24 16:35:46 +01:00
9f1ce26d6e Even better faucet logging (#209)
* speed up tx lock

* faucet logging

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 16:35:27 +01:00
gohumbleandGitHub 0ce42e8f1f do not cancel inactive faucet (#208)
* fix logs

* remove cancel faucet if not active
2021-12-24 16:04:36 +01:00
46d77de38e fix faucet balance to low panic (#207)
Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-24 15:57:23 +01:00
09d3af411e Better longging 1337 (#206)
* speed up tx lock

* better logging and lnurl lightning: prefix

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 15:34:17 +01:00
5414c82339 Logging mutex fix (#205)
* speed up tx lock

* better logging

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 15:00:55 +01:00
LightningTipBotandGitHub 2edc2953dc Revert "Min faucet 1 (#203)" (#204)
This reverts commit 2bc9555b53.
2021-12-24 14:46:32 +01:00
2bc9555b53 Min faucet 1 (#203)
* speed up tx lock

* reduce min faucet

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 14:37:49 +01:00
gohumbleandGitHub 47ef5baee3 fix mutex final last v2 maybe (#202)
* remove mutex on unlock

* add pprof

* fix mutex lock

* fix logs
2021-12-24 14:25:35 +01:00
78eadf1a0e Tip fix lock (#201)
* speed up tx lock

* tip fix lock

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 02:43:21 +01:00
gohumbleandGitHub 6aa05c8faa Callback response (#200)
* add answerCallbackInterceptor

* use answerCallbackInterceptor

* fix nil response
2021-12-24 02:22:41 +01:00
8f8644a1d2 Faucet panic (#199)
* speed up tx lock

* remove panic

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 01:45:07 +01:00
f9aed70869 Soft lock (#198)
* add Lock and Unlock soft

* Update mutex.go

* sync mutex

* mutex bracket

* add idInterceptor

* context lock

Co-authored-by: lngohumble <lngohumble@gmail.com>
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-24 00:12:57 +01:00
036ac12f41 Lnurlpay pointer fix (#197)
* speed up tx lock

* fix pointer

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-23 21:52:58 +01:00
LightningTipBotandGitHub 67cff58c63 Revert "Soft lock (#195)" (#196)
This reverts commit 4730c94c84.
2021-12-23 19:29:14 +01:00
4730c94c84 Soft lock (#195)
* add Lock and Unlock soft

* Update mutex.go

Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-23 19:25:55 +01:00
LightningTipBotandGitHub e53ef94306 Revert "add Lock and Unlock soft (#193)" (#194)
This reverts commit a9f2728c93.
2021-12-23 19:08:06 +01:00
gohumbleandGitHub a9f2728c93 add Lock and Unlock soft (#193) 2021-12-23 19:06:15 +01:00
gohumbleandGitHub 657fc7af1d fix mutex (#192) 2021-12-23 17:18:04 +01:00
gohumbleandGitHub 1b24072020 Interface conversion (#191)
* remove user mutex log message

* add bunt cache

* fix send and pay data pointer conversion
2021-12-23 17:07:41 +01:00
d912541391 Faucet set after validation (#190)
* speed up tx lock

* faucet set after validation

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-23 16:55:39 +01:00
gohumbleandGitHub 72381d0071 Bunt cache (#189)
* remove user mutex log message

* add bunt cache
2021-12-23 16:52:24 +01:00
a644c465cd Disable bunt lock (#188)
* speed up tx lock

* transaction to storage

* to base

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-23 16:23:57 +01:00
gohumbleandGitHub bc0d3df897 Fix log (#187)
* remove user mutex log message

* remove log

* fix bunt locks log messages
2021-12-23 15:57:48 +01:00
gohumbleandGitHub fa234d4073 remove user mutex log message (#186) 2021-12-23 15:50:41 +01:00
gohumbleandGitHub dd88c93474 add mutex package (#185)
* add mutex package

* fix cancelSendHandler
2021-12-23 15:47:18 +01:00
2469898f9f Inline lock fix (#184)
* speed up tx lock

* fix get

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-23 15:12:49 +01:00
ee656dc5f0 Mutex fix 420 (#183)
* speed up tx lock

* handling

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-23 11:16:26 +01:00
3eba0de851 Tiptopptiptiptopbranch (#182)
* speed up tx lock

* tiptooltip better

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-23 10:43:43 +01:00
f8fadb1729 Onlysats (#181)
* speed up tx lock

* add shops

* shop

* scrolling

* 🚀 add state stateCallbackMessage 🚀

* no shop

* scroll

* add shop browser

* scroll bug

* add buttons.go

* scrolling

* shop

* lnurl print after serving

* shop deletion

* adding and removing shops

* display photo captions

* refactor

* shops

* shops

* files work

* rename shop

* error handling

* fixes

* payments

* confirm delete all shops

* adding new items fix

* own bunt db for shop

* unlock transaction

* remove double print

* add transaction.Lock(id)

* unlock getShop

* add default interceptors to shop

* more files

* go sleep

* add fileStateResetTicker

* async sleep

* add runtime.ResettableFunctionTicker

* remove default duration

* generalized concurrent mutex

* simplify function ticker

* status message ticker queue

* add start index to shopViewDeleteAllStatusMsgs

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-23 10:16:13 +01:00
gohumbleandGitHub 6b5e30dbe4 Fix tx lock (#180)
* unlock tx mutex on GET error

* log tx id on timeout
2021-12-22 19:24:51 +01:00
gohumbleandGitHub 72ef490538 unlock tx mutex on GET error (#179) 2021-12-22 19:13:21 +01:00
gohumbleandGitHub 7e2404eaf5 add transaction mutex lock (#178) 2021-12-22 18:54:06 +01:00
gohumbleandGitHub 64f9492af2 update no private chat error message (#177) 2021-12-22 18:03:03 +01:00
gohumbleandGitHub f85ec34bcc fix lock intercept (#176) 2021-12-22 17:48:30 +01:00
8b40253169 remove default interceptors (#174)
* defer intercept after before intercept error check.

* log trace level

* get rid of default interceptors

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-22 17:34:57 +01:00
91d38b5bb4 Faucet debug logging (#175)
* speed up tx lock

* add logging

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-22 17:33:14 +01:00
a59a7c226d defer intercept after before intercept error check (#173)
* defer intercept after before intercept error check.

* log trace level

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-22 14:40:48 +01:00
4b620186f1 Lnbits postgres compatible (#172)
* speed up tx lock

* webhook fix

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-22 02:35:00 +01:00
f313b5cdbe Faucet no tx error (#171)
* speed up tx lock

* remove tx timeout errors

* cacel faucet on error

* cancle faucet on error

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-21 16:16:42 +01:00
179d40178c Faucet no tx error (#170)
* speed up tx lock

* remove tx timeout errors

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-21 16:07:26 +01:00
LightningTipBotandGitHub 15d711a6fd Tipjar fix usercheck (#169)
* check for correct user for tipjar
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-19 18:51:49 +01:00
a4f5b21f1d Invoice events refactoring (#168)
* speed up tx lock

* clean up

* refactor lnurl comment notification

* fix function name

* transaction: do not check balance; refactor invoice notifications

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-19 15:41:01 +01:00
307d9cd873 Debug tip tooltip missing (#167)
* speed up tx lock

* debug for tip

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-18 18:05:48 +00:00
0f6c37a40c Check balance inline receive (#166)
* speed up tx lock

* check balance

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-17 20:47:22 +00:00
9e4b612c26 Invoice events for inline receive (#164)
* speed up tx lock

* receive via invoice

* update telebot to save message InlineID

* remove debug ifs

* correct response

* comment

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-17 20:41:13 +00:00
1815bcfaf9 Receive button order (#163)
* receive button reorder

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-17 09:51:52 +00:00
6299adf633 Faucet per_user minimum 5 sat, Tipjar Button reverse (#162)
* tipjar and faucet change

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-14 19:44:16 +01:00
5b93d43bc5 speed up tx lock (#161)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-14 18:06:37 +01:00
0cfb693619 int64 amounts (#159)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-11 23:17:51 +01:00
1ea9268698 better (#160)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-11 22:09:52 +01:00
f50e6ced71 test mutex (#158)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-08 22:22:11 +01:00
gohumbleandGitHub 1b922c03a9 mutex interceptor patch to prevent concurrent map read / write (#157)
* add handlerMapMutex

* cleanup
2021-12-08 09:55:56 +01:00
f6768b72ea Mutex lock per Telegram User ID (#156)
* lets go

* dunno

* fix after interceptor

* getTelegramUserFromInterface

* clean up requireUserInterceptor

* clean up bs

* cleanup

* cleanup2

* add comment

* fix before default interceptor

* async sleep

* back to 60

* remove newline

* adding defer interceptor

* handlers tighter

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-07 22:55:21 +01:00
236b095bbe new telebot (#155)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-07 20:06:17 +01:00
gohumbleandGitHub a0799b1b32 isAdminAndCanEdit fix (#154)
* Update telegram.go

* remove isAdminAndCanEdit on tryEdit

* remove isAdminAndCanEdit
2021-12-07 10:34:37 +01:00
51 changed files with 3724 additions and 690 deletions
+2 -1
View File
@@ -12,6 +12,7 @@ require (
github.com/jinzhu/configor v1.2.1
github.com/makiuchi-d/gozxing v0.0.2
github.com/nicksnyder/go-i18n/v2 v2.1.2
github.com/orcaman/concurrent-map v1.0.0
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/sethvargo/go-limiter v0.7.2
github.com/sirupsen/logrus v1.6.0
@@ -20,7 +21,7 @@ require (
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.v2 v2.4.2-0.20211201074627-babf9f2cc955
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211217193303-c005cce171ac
gorm.io/driver/sqlite v1.1.4
gorm.io/gorm v1.21.12
)
+8
View File
@@ -397,6 +397,8 @@ github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxS
github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw=
github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4=
github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4=
github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HDbW65HOY=
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM=
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
@@ -728,6 +730,10 @@ gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201070229-f317e8453e9f h1:BnYl
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201070229-f317e8453e9f/go.mod h1:lUH49SRidDcQGyXPIL9tR2cN3vztcLBo47AqFUgHgIA=
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201074627-babf9f2cc955 h1:uhQUyDqilPUh58BWtIeSAupjovs1QQjC6pEoErqD86o=
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201074627-babf9f2cc955/go.mod h1:lUH49SRidDcQGyXPIL9tR2cN3vztcLBo47AqFUgHgIA=
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211207185736-224e4f70c5ad h1:HR3vqf1DS7hEQ0j77J4ctumZgzDIHNXZtag60U9OOig=
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/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=
@@ -738,6 +744,8 @@ gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkep
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=
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637/go.mod h1:BHsqpu/nsuzkT5BpiH1EMZPLyqSMM8JbIavyFACoFNk=
gopkg.in/tucnak/telebot.v2 v2.4.1 h1:bUOFHtHhuhPekjHGe1Q1BmITvtBLdQI4yjSMC405KcU=
gopkg.in/tucnak/telebot.v2 v2.4.1/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI=
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+1
View File
@@ -30,6 +30,7 @@ type TelegramConfiguration struct {
}
type DatabaseConfiguration struct {
DbPath string `yaml:"db_path"`
ShopBuntDbPath string `yaml:"shop_buntdb_path"`
BuntDbPath string `yaml:"buntdb_path"`
TransactionsPath string `yaml:"transactions_path"`
}
+7
View File
@@ -36,6 +36,13 @@ const (
UserHasEnteredAmount
UserEnterUser
UserHasEnteredUser
UserEnterShopTitle
UserStateShopItemSendPhoto
UserStateShopItemSendTitle
UserStateShopItemSendDescription
UserStateShopItemSendPrice
UserStateShopItemSendItemFile
UserEnterShopsDescription
)
type UserStateKey int
+34 -37
View File
@@ -7,7 +7,6 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
log "github.com/sirupsen/logrus"
@@ -15,7 +14,6 @@ import (
"net/http"
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/gorilla/mux"
@@ -24,10 +22,6 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
)
const (
// invoiceReceivedMessage = "⚡️ You received %d sat."
)
type Server struct {
httpServer *http.Server
bot *tb.Bot
@@ -37,17 +31,16 @@ type Server struct {
}
type Webhook struct {
CheckingID string `json:"checking_id"`
Pending int `json:"pending"`
Amount int `json:"amount"`
Fee int `json:"fee"`
Memo string `json:"memo"`
Time int `json:"time"`
Bolt11 string `json:"bolt11"`
Preimage string `json:"preimage"`
PaymentHash string `json:"payment_hash"`
Extra struct {
} `json:"extra"`
CheckingID string `json:"checking_id"`
Pending bool `json:"pending"`
Amount int64 `json:"amount"`
Fee int64 `json:"fee"`
Memo string `json:"memo"`
Time int64 `json:"time"`
Bolt11 string `json:"bolt11"`
Preimage string `json:"preimage"`
PaymentHash string `json:"payment_hash"`
Extra struct{} `json:"extra"`
WalletID string `json:"wallet_id"`
Webhook string `json:"webhook"`
WebhookStatus interface{} `json:"webhook_status"`
@@ -55,8 +48,7 @@ type Webhook struct {
func NewServer(bot *telegram.TipBot) *Server {
srv := &http.Server{
Addr: internal.Configuration.Lnbits.WebhookServerUrl.Host,
// Good practice: enforce timeouts for servers you create!
Addr: internal.Configuration.Lnbits.WebhookServerUrl.Host,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
@@ -88,38 +80,43 @@ func (w *Server) newRouter() *mux.Router {
return router
}
func (w Server) receive(writer http.ResponseWriter, request *http.Request) {
depositEvent := Webhook{}
func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
log.Debugln("[Webhook] Received request")
webhookEvent := Webhook{}
// need to delete the header otherwise the Decode will fail
request.Header.Del("content-length")
err := json.NewDecoder(request.Body).Decode(&depositEvent)
err := json.NewDecoder(request.Body).Decode(&webhookEvent)
if err != nil {
log.Errorf("[Webhook] Error decoding request: %s", err.Error())
writer.WriteHeader(400)
return
}
user, err := w.GetUserByWalletId(depositEvent.WalletID)
user, err := w.GetUserByWalletId(webhookEvent.WalletID)
if err != nil {
log.Errorf("[Webhook] Error getting user: %s", err.Error())
writer.WriteHeader(400)
return
}
log.Infoln(fmt.Sprintf("[⚡️ WebHook] User %s (%d) received invoice of %d sat.", telegram.GetUserStr(user.Telegram), user.Telegram.ID, depositEvent.Amount/1000))
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), depositEvent.Amount/1000))
if err != nil {
log.Errorln(err)
}
log.Infoln(fmt.Sprintf("[⚡️ WebHook] User %s (%d) received invoice of %d sat.", telegram.GetUserStr(user.Telegram), user.Telegram.ID, webhookEvent.Amount/1000))
// if this invoice is saved in bunt.db, we load it and display the comment from an LNURL invoice
tx := &lnurl.Invoice{PaymentHash: depositEvent.PaymentHash}
err = w.buntdb.Get(tx)
writer.WriteHeader(200)
// trigger invoice events
txInvoiceEvent := &telegram.InvoiceEvent{Invoice: &telegram.Invoice{PaymentHash: webhookEvent.PaymentHash}}
err = w.buntdb.Get(txInvoiceEvent)
if err != nil {
log.Errorln(err)
} else {
if len(tx.Comment) > 0 {
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(`✉️ %s`, str.MarkdownEscape(tx.Comment)))
if err != nil {
log.Errorln(err)
}
// do something with the event
if c := telegram.InvoiceCallback[txInvoiceEvent.Callback]; c != nil {
c(txInvoiceEvent)
return
}
}
writer.WriteHeader(200)
// fallback: send a message to the user if there is no callback for this invoice
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), webhookEvent.Amount/1000))
if err != nil {
log.Errorln(err)
}
}
+33 -24
View File
@@ -11,24 +11,23 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/fiatjaf/go-lnurl"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
type Invoice struct {
PaymentRequest string `json:"payment_request"`
PaymentHash string `json:"payment_hash"`
Amount int64 `json:"amount"`
Comment string `json:"comment"`
ToUser *lnbits.User `json:"to_user"`
CreatedAt time.Time `json:"created_at"`
Paid bool `json:"paid"`
PaidAt time.Time `json:"paid_at"`
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"`
}
func (msg Invoice) Key() string {
return fmt.Sprintf("payment-hash:%s", msg.PaymentHash)
func (lnurlInvoice LNURLInvoice) Key() string {
return fmt.Sprintf("lnurl-p:%s", lnurlInvoice.PaymentHash)
}
func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
@@ -58,7 +57,7 @@ func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
// check if error was returned from first or second handlers
if err != nil {
// log the error
log.Errorf("[LNURL] %v", err)
log.Errorf("[LNURL] %v", err.Error())
if response != nil {
// there is a valid error response
err = writeResponse(writer, response)
@@ -98,9 +97,9 @@ func (w Server) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error)
}
// serveLNURLpSecond serves the second LNURL response with the payment request with the correct description hash
func (w Server) serveLNURLpSecond(username string, amount int64, comment string) (*lnurl.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 < minSendable || amount > MaxSendable {
if amount_msat < minSendable || amount_msat > MaxSendable {
// amount is not ok
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
@@ -156,13 +155,13 @@ func (w Server) serveLNURLpSecond(username string, amount int64, comment string)
}
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Amount: amount / 1000,
Amount: amount_msat / 1000,
Out: false,
DescriptionHash: descriptionHash,
Webhook: w.WebhookServer},
w.c)
if err != nil {
err = fmt.Errorf("[serveLNURLpSecond] Couldn't create invoice: %v", err)
err = fmt.Errorf("[serveLNURLpSecond] Couldn't create invoice: %v", err.Error())
resp = &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: statusError,
@@ -170,15 +169,25 @@ func (w Server) serveLNURLpSecond(username string, amount int64, comment string)
}
return resp, err
}
// save invoice struct for later use
invoiceStruct := &telegram.Invoice{
PaymentRequest: invoice.PaymentRequest,
PaymentHash: invoice.PaymentHash,
Amount: amount_msat / 1000,
}
// save lnurl invoice struct for later use (will hold the comment or other metdata for a notification when paid)
runtime.IgnoreError(w.buntdb.Set(
Invoice{
ToUser: user,
Amount: amount,
Comment: comment,
PaymentRequest: invoice.PaymentRequest,
PaymentHash: invoice.PaymentHash,
CreatedAt: time.Now(),
LNURLInvoice{
Invoice: invoiceStruct,
User: user,
Comment: comment,
CreatedAt: time.Now(),
}))
// save the invoice Event that will be loaded when the invoice is paid and trigger the comment display callback
runtime.IgnoreError(w.buntdb.Set(
telegram.InvoiceEvent{
Invoice: invoiceStruct,
User: user,
Callback: telegram.InvoiceCallbackLNURLPayReceive,
}))
return &lnurl.LNURLPayValues{
+3 -3
View File
@@ -62,7 +62,7 @@ func (p *PriceWatcher) Watch() error {
for currency, _ := range p.Currencies {
avg_price := 0.0
n_responses := 0
for exchange, getPrice := range p.Exchanges {
for _, getPrice := range p.Exchanges {
fprice, err := getPrice(currency)
if err != nil {
// log.Debug(err)
@@ -71,11 +71,11 @@ func (p *PriceWatcher) Watch() error {
}
n_responses++
avg_price += fprice
log.Debugf("[PriceWatcher] %s %s price: %f", exchange, currency, fprice)
// log.Debugf("[PriceWatcher] %s %s price: %f", exchange, currency, fprice)
time.Sleep(time.Second * time.Duration(2))
}
Price[currency] = avg_price / float64(n_responses)
log.Debugf("[PriceWatcher] Average %s price: %f", currency, Price[currency])
// log.Debugf("[PriceWatcher] Average %s price: %f", currency, Price[currency])
}
time.Sleep(p.UpdateInterval)
}
+4 -3
View File
@@ -2,10 +2,11 @@ package rate
import (
"context"
"golang.org/x/time/rate"
tb "gopkg.in/lightningtipbot/telebot.v2"
"strconv"
"sync"
"golang.org/x/time/rate"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
// Limiter
@@ -21,7 +22,7 @@ var globalLimiter *rate.Limiter
// NewLimiter creates both chat and global rate limiters.
func Start() {
idLimiter = newIdRateLimiter(rate.Limit(0.3), 20)
idLimiter = newIdRateLimiter(rate.Limit(0.25), 20)
globalLimiter = rate.NewLimiter(rate.Limit(30), 30)
}
+76
View File
@@ -0,0 +1,76 @@
package runtime
import (
cmap "github.com/orcaman/concurrent-map"
"time"
)
var tickerMap cmap.ConcurrentMap
func init() {
tickerMap = cmap.New()
}
var defaultTickerCoolDown = time.Second * 10
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
type ResettableFunctionTicker struct {
Ticker *time.Ticker
ResetChan chan struct{} // channel used to reset the ticker
duration time.Duration
Started bool
name string
}
type ResettableFunctionTickerOption func(*ResettableFunctionTicker)
func WithDuration(d time.Duration) ResettableFunctionTickerOption {
return func(a *ResettableFunctionTicker) {
a.duration = d
}
}
func RemoveTicker(name string) {
tickerMap.Remove(name)
}
func GetTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
if t, ok := tickerMap.Get(name); ok {
return t.(*ResettableFunctionTicker)
} else {
t := NewResettableFunctionTicker(name, option...)
tickerMap.Set(name, t)
return t
}
}
func NewResettableFunctionTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
t := &ResettableFunctionTicker{
ResetChan: make(chan struct{}, 1),
name: name,
}
for _, opt := range option {
opt(t)
}
if t.duration == 0 {
t.duration = defaultTickerCoolDown
}
t.Ticker = time.NewTicker(t.duration)
return t
}
func (t *ResettableFunctionTicker) Do(f func()) {
t.Started = true
tickerMap.Set(t.name, t)
go func() {
for {
select {
case <-t.Ticker.C:
// ticker delivered signal. do function f
f()
return
case <-t.ResetChan:
// reset signal received. creating new ticker.
t.Ticker = time.NewTicker(t.duration)
}
}
}()
}
+95
View File
@@ -0,0 +1,95 @@
package mutex
import (
"context"
"fmt"
"sync"
cmap "github.com/orcaman/concurrent-map"
log "github.com/sirupsen/logrus"
)
var mutexMap cmap.ConcurrentMap
func init() {
mutexMap = cmap.New()
}
// checkSoftLock checks in mutexMap how often an existing mutex was already SoftLocked.
// The counter is there to avoid multiple recursive locking of an object in the mutexMap.
// This happens if multiple handlers call each other and try to lock/unlock multiple times
// the same mutex.
func checkSoftLock(s string) int {
if v, ok := mutexMap.Get(fmt.Sprintf("nLocks:%s", s)); ok {
return v.(int)
}
return 0
}
// LockWithContext locks a mutex only if it hasn't been locked before in a context.
// LockWithContext should be used to lock objects like faucets etc.
// The context carries a uid that is unique the each request (message, button press, etc.).
// If the uid has a lock already *for a certain object*, it increments the
// nLocks in the mutexMap. If not, it locks the object. This is supposed to lock only if nLock == 0.
func LockWithContext(ctx context.Context, s string) {
uid := ctx.Value("uid").(string)
// sync mutex to sync checkSoftLock with the increment of nLocks
// same user can't lock the same object multiple times
Lock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
var nLocks = checkSoftLock(uid)
if nLocks == 0 {
Lock(s)
} else {
log.Tracef("[Mutex] Skip lock (nLocks: %d)", nLocks)
}
nLocks++
mutexMap.Set(fmt.Sprintf("nLocks:%s", uid), nLocks)
Unlock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
}
// UnlockWithContext unlock a mutex only if it has been locked once within a context.
// If it has been locked more than once
// it only decrements nLocks and skips the unlock of the mutex. This is supposed to unlock only for
// nLocks == 1
func UnlockWithContext(ctx context.Context, s string) {
uid := ctx.Value("uid").(string)
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)
} else {
log.Tracef("[Mutex] Skip unlock (nLocks: %d)", nLocks)
}
Unlock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
mutexMap.Remove(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
}
// Lock locks a mutex in the mutexMap. If the mutex is already in the map, it locks the current call.
// After it another call unlocks the mutex (and deletes it from the mutexMap) the mutex written again into the mutexMap.
// If the mutex was not in the mutexMap before, a new mutext is created and locked and written into the mutexMap.
func Lock(s string) {
log.Tracef("[Mutex] Attempt Lock %s", s)
if m, ok := mutexMap.Get(s); ok {
m.(*sync.Mutex).Lock()
mutexMap.Set(s, m)
} else {
m := &sync.Mutex{}
m.Lock()
mutexMap.Set(s, m)
}
log.Tracef("[Mutex] Locked %s", s)
}
// Unlock unlocks a mutex in the mutexMap.
func Unlock(s string) {
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)
}
}
+49
View File
@@ -0,0 +1,49 @@
package once
import (
"fmt"
cmap "github.com/orcaman/concurrent-map"
log "github.com/sirupsen/logrus"
)
var onceMap cmap.ConcurrentMap
func init() {
onceMap = cmap.New()
}
func New(objectKey string) {
onceMap.Set(objectKey, cmap.New())
}
// Once creates a map of keys k1 with a map of keys k2.
// The idea is that an object with ID k1 can create a list of users k2
// that have already interacted with the object. If the user k2 is in the list,
// the object is not allowed to accessed again.
func Once(k1, k2 string) error {
i, ok := onceMap.Get(k1)
if ok {
return setOrReturn(i.(cmap.ConcurrentMap), k2)
}
userMap := cmap.New()
onceMap.Set(k1, userMap)
log.Tracef("[Once] Added key %s to onceMap (len=%d)", k1, len(onceMap.Keys()))
return setOrReturn(userMap, k2)
}
// setOrReturn sets the key k2 in the map i if it is not already set.
func setOrReturn(objectMap cmap.ConcurrentMap, k2 string) error {
if _, ok := objectMap.Get(k2); ok {
return fmt.Errorf("%s already consumed object", k2)
}
objectMap.Set(k2, true)
return nil
}
// Remove removes the key k1 from the map. Should be called after Once was called and
// the object k1 finished.
func Remove(k1 string) {
onceMap.Remove(k1)
log.Tracef("[Once] Removed key %s from onceMap (len=%d)", k1, len(onceMap.Keys()))
}
+91
View File
@@ -0,0 +1,91 @@
package storage
import (
"time"
"github.com/eko/gocache/store"
gocache "github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
)
var transactionCache = store.NewGoCache(gocache.New(5*time.Minute, 10*time.Minute), nil)
type Base struct {
ID string `json:"id"`
Active bool `json:"active"`
Canceled bool `json:"canceled"`
CreatedAt time.Time `json:"created"`
UpdatedAt time.Time `json:"updated"`
}
type Option func(b *Base)
func ID(id string) Option {
return func(btx *Base) {
btx.ID = id
}
}
func New(opts ...Option) *Base {
btx := &Base{
Active: true,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
for _, opt := range opts {
opt(btx)
}
return btx
}
func (tx Base) Key() string {
return tx.ID
}
func (tx *Base) Inactivate(s Storable, db *DB) error {
tx.Active = false
err := tx.Set(s, db)
if err != nil {
log.Tracef("[Bunt Inactivate] %s Error: %s", tx.ID, err.Error())
return err
}
log.Tracef("[Bunt Inactivate] %s", tx.ID)
return nil
}
func (tx *Base) Get(s Storable, db *DB) (Storable, error) {
cacheTx, err := transactionCache.Get(s.Key())
if err != nil {
err := db.Get(s)
if err != nil {
return s, err
}
log.Tracef("[Bunt] get object %s", s.Key())
return s, transactionCache.Set(s.Key(), s, &store.Options{Expiration: 5 * time.Minute})
}
log.Tracef("[Bunt Cache] get object %s", s.Key())
return cacheTx.(Storable), err
}
func (tx *Base) Set(s Storable, db *DB) error {
tx.UpdatedAt = time.Now()
err := db.Set(s)
if err != nil {
log.Errorf("[Bunt] could not set object: %v", err.Error())
return err
}
log.Tracef("[Bunt] set object %s", s.Key())
err = transactionCache.Set(s.Key(), s, &store.Options{Expiration: 5 * time.Minute})
if err != nil {
log.Errorf("[Bunt Cache] could not set object: %v", err.Error())
}
log.Tracef("[Bunt Cache] set object: %s", s.Key())
return err
}
func (tx *Base) Delete(s Storable, db *DB) error {
tx.UpdatedAt = time.Now()
return db.Delete(s.Key(), s)
}
+23 -15
View File
@@ -2,7 +2,7 @@ package storage
import (
"encoding/json"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
log "github.com/sirupsen/logrus"
"github.com/tidwall/buntdb"
)
@@ -78,23 +78,31 @@ func (db *DB) Set(object Storable) error {
}
// Delete a storable item.
// todo -- not ascend users index
func (db *DB) Delete(index string, object Storable) error {
return db.Update(func(tx *buntdb.Tx) error {
var delkeys []string
runtime.IgnoreError(
tx.Ascend(index, func(key, value string) bool {
if key == object.Key() {
delkeys = append(delkeys, key)
}
return true
}),
)
for _, k := range delkeys {
if _, err := tx.Delete(k); err != nil {
return err
}
_, err := tx.Get(object.Key())
if err != nil {
return err
}
if _, err := tx.Delete(object.Key()); err != nil {
return err
}
// OLD: from gohumble:
// todo -- not ascend users index
// var delkeys []string
// runtime.IgnoreError(
// tx.Ascend(index, func(key, value string) bool {
// if key == object.Key() {
// delkeys = append(delkeys, key)
// }
// return true
// }),
// )
// for _, k := range delkeys {
// if _, err := tx.Delete(k); err != nil {
// return err
// }
// }
return nil
})
}
@@ -1,98 +0,0 @@
package transaction
import (
"fmt"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
)
type Base struct {
ID string `json:"id"`
Active bool `json:"active"`
InTransaction bool `json:"intransaction"`
CreatedAt time.Time `json:"created"`
UpdatedAt time.Time `json:"updated"`
}
type Option func(b *Base)
func ID(id string) Option {
return func(btx *Base) {
btx.ID = id
}
}
func New(opts ...Option) *Base {
btx := &Base{
Active: true,
InTransaction: false,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
for _, opt := range opts {
opt(btx)
}
return btx
}
func (tx Base) Key() string {
return tx.ID
}
func (tx *Base) Lock(s storage.Storable, db *storage.DB) error {
// immediatelly set intransaction to block duplicate calls
tx.InTransaction = true
err := tx.Set(s, db)
if err != nil {
return err
}
return nil
}
func (tx *Base) Release(s storage.Storable, db *storage.DB) error {
// immediatelly set intransaction to block duplicate calls
tx.InTransaction = false
err := tx.Set(s, db)
if err != nil {
return err
}
return nil
}
func (tx *Base) Inactivate(s storage.Storable, db *storage.DB) error {
tx.Active = false
err := tx.Set(s, db)
if err != nil {
return err
}
return nil
}
func (tx *Base) Get(s storage.Storable, db *storage.DB) (storage.Storable, error) {
err := db.Get(s)
if err != nil {
return s, err
}
// to avoid race conditions, we block the call if there is
// already an active transaction by loop until InTransaction is false
ticker := time.NewTicker(time.Second * 3)
for tx.InTransaction {
select {
case <-ticker.C:
return nil, fmt.Errorf("transaction timeout")
default:
time.Sleep(time.Duration(200) * time.Millisecond)
err = db.Get(s)
}
}
if err != nil {
return nil, fmt.Errorf("could not get transaction")
}
return s, nil
}
func (tx *Base) Set(s storage.Storable, db *storage.DB) error {
tx.UpdatedAt = time.Now()
return db.Set(s)
}
+15 -9
View File
@@ -8,10 +8,12 @@ import (
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/price"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
@@ -24,7 +26,7 @@ func getArgumentFromCommand(input string, which int) (output string, err error)
return output, nil
}
func decodeAmountFromCommand(input string) (amount int, err error) {
func decodeAmountFromCommand(input string) (amount int64, err error) {
if len(strings.Split(input, " ")) < 2 {
errmsg := "message doesn't contain any amount"
// log.Errorln(errmsg)
@@ -34,14 +36,14 @@ func decodeAmountFromCommand(input string) (amount int, err error) {
return amount, err
}
func getAmount(input string) (amount int, err error) {
func getAmount(input string) (amount int64, err error) {
// convert something like 1.2k into 1200
if strings.HasSuffix(strings.ToLower(input), "k") {
fmount, err := strconv.ParseFloat(strings.TrimSpace(input[:len(input)-1]), 64)
if err != nil {
return 0, err
}
amount = int(fmount * 1000)
amount = int64(fmount * 1000)
return amount, err
}
@@ -61,13 +63,13 @@ func getAmount(input string) (amount int, err error) {
if !(price.Price[currency] > 0) {
return 0, errors.New("price is zero")
}
amount = int(fmount / price.Price[currency] * float64(100_000_000))
amount = int64(fmount / price.Price[currency] * float64(100_000_000))
return amount, nil
}
}
// use plain integer as satoshis
amount, err = strconv.Atoi(input)
amount, err = strconv.ParseInt(input, 10, 64)
if err != nil {
return 0, err
}
@@ -145,7 +147,7 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
}
// amount not in allowed range from LNURL
if EnterAmountStateData.AmountMin > 0 && EnterAmountStateData.AmountMax >= EnterAmountStateData.AmountMin && // this line checks whether min_max is set at all
(amount > int(EnterAmountStateData.AmountMax/1000) || amount < int(EnterAmountStateData.AmountMin/1000)) { // this line then checks whether the amount is in the range
(amount > int64(EnterAmountStateData.AmountMax/1000) || amount < int64(EnterAmountStateData.AmountMin/1000)) { // this line then checks whether the amount is in the range
err = fmt.Errorf("amount not in range")
log.Warnf("[enterAmountHandler] %s", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), EnterAmountStateData.AmountMin/1000, EnterAmountStateData.AmountMax/1000))
@@ -157,7 +159,9 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
// we stored this in the EnterAmountStateData before
switch EnterAmountStateData.Type {
case "LnurlPayState":
tx := &LnurlPayState{Base: transaction.New(transaction.ID(EnterAmountStateData.ID))}
tx := &LnurlPayState{Base: storage.New(storage.ID(EnterAmountStateData.ID))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
return
@@ -177,7 +181,9 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
bot.lnurlPayHandlerSend(ctx, m)
return
case "LnurlWithdrawState":
tx := &LnurlWithdrawState{Base: transaction.New(transaction.ID(EnterAmountStateData.ID))}
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
+7 -4
View File
@@ -14,7 +14,6 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/storage"
gocache "github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
"gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
"gorm.io/gorm"
)
@@ -22,8 +21,9 @@ import (
type TipBot struct {
Database *gorm.DB
Bunt *storage.DB
ShopBunt *storage.DB
logger *gorm.DB
Telegram *telebot.Bot
Telegram *tb.Bot
Client *lnbits.Client
limiter map[string]limiter.Limiter
Cache
@@ -48,7 +48,8 @@ func NewBot() TipBot {
Database: db,
Client: lnbits.NewClient(internal.Configuration.Lnbits.AdminKey, internal.Configuration.Lnbits.Url),
logger: txLogger,
Bunt: createBunt(),
Bunt: createBunt(internal.Configuration.Database.BuntDbPath),
ShopBunt: createBunt(internal.Configuration.Database.ShopBuntDbPath),
Telegram: newTelegramBot(),
Cache: Cache{GoCacheStore: gocacheStore},
}
@@ -81,7 +82,7 @@ func (bot TipBot) initBotWallet() error {
}
// Start will initialize the Telegram bot and lnbits.
func (bot TipBot) Start() {
func (bot *TipBot) Start() {
log.Infof("[Telegram] Authorized on account @%s", bot.Telegram.Me.Username)
// initialize the bot wallet
err := bot.initBotWallet()
@@ -89,5 +90,7 @@ func (bot TipBot) Start() {
log.Errorf("Could not initialize bot wallet: %s", err.Error())
}
bot.registerTelegramHandlers()
initInvoiceEventCallbacks(bot)
initializeStateCallbackMessage(bot)
bot.Telegram.Start()
}
+47
View File
@@ -0,0 +1,47 @@
package telegram
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 (
CommandSend = "💸 Send"
CommandBalance = "👑 Balance"
CommandInvoice = "⚡️ Invoice"
CommandHelp = "📖 Help"
)
var (
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, btnHelpMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu),
)
}
// buttonWrapper wrap buttons slice in rows of length i
func buttonWrapper(buttons []tb.Btn, markup *tb.ReplyMarkup, length int) []tb.Row {
buttonLength := len(buttons)
rows := make([]tb.Row, 0)
if buttonLength > length {
for i := 0; i < buttonLength; i = i + length {
buttonRow := make([]tb.Btn, length)
if i+length < buttonLength {
buttonRow = buttons[i : i+length]
} else {
buttonRow = buttons[i:]
}
rows = append(rows, markup.Row(buttonRow...))
}
return rows
}
rows = append(rows, markup.Row(buttons...))
return rows
}
+2 -2
View File
@@ -26,9 +26,9 @@ const (
TipTooltipKeyPattern = "tip-tool-tip:*"
)
func createBunt() *storage.DB {
func createBunt(file string) *storage.DB {
// create bunt database
bunt := storage.NewBunt(internal.Configuration.Database.BuntDbPath)
bunt := storage.NewBunt(file)
// create bunt database index for ascending (searching) TipTooltips
err := bunt.CreateIndex(MessageOrderedByReplyToFrom, TipTooltipKeyPattern, buntdb.IndexJSON(MessageOrderedByReplyToFrom))
if err != nil {
+32
View File
@@ -0,0 +1,32 @@
package telegram
import (
"context"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func (bot *TipBot) fileHandler(ctx context.Context, m *tb.Message) {
if m.Chat.Type != tb.ChatPrivate {
return
}
user := LoadUser(ctx)
if c := stateCallbackMessage[user.StateKey]; c != nil {
// 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, 0)
runtime.RemoveTicker(user.ID)
})
} else {
ticker.ResetChan <- struct{}{}
}
c(ctx, m)
return
}
}
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -34,7 +34,7 @@ func GetMemoFromCommand(command string, fromWord int) string {
return memo
}
func MakeProgressbar(current int, total int) string {
func MakeProgressbar(current int64, total int64) string {
MAX_BARS := 16
progress := math.Round((float64(current) / float64(total)) * float64(MAX_BARS))
progressbar := strings.Repeat("🟩", int(progress))
@@ -42,7 +42,7 @@ func MakeProgressbar(current int, total int) string {
return progressbar
}
func MakeTipjarbar(current int, total int) string {
func MakeTipjarbar(current int64, total int64) string {
MAX_BARS := 16
progress := math.Round((float64(current) / float64(total)) * float64(MAX_BARS))
progressbar := strings.Repeat("🍯", int(progress))
+146 -109
View File
@@ -3,16 +3,20 @@ package telegram
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/once"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/eko/gocache/store"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
log "github.com/sirupsen/logrus"
@@ -25,18 +29,20 @@ var (
btnAcceptInlineFaucet = inlineFaucetMenu.Data("✅ Collect", "confirm_faucet_inline")
)
type InlineFaucet struct {
*transaction.Base
Message string `json:"inline_faucet_message"`
Amount int `json:"inline_faucet_amount"`
RemainingAmount int `json:"inline_faucet_remainingamount"`
PerUserAmount int `json:"inline_faucet_peruseramount"`
From *lnbits.User `json:"inline_faucet_from"`
To []*lnbits.User `json:"inline_faucet_to"`
Memo string `json:"inline_faucet_memo"`
NTotal int `json:"inline_faucet_ntotal"`
NTaken int `json:"inline_faucet_ntaken"`
UserNeedsWallet bool `json:"inline_faucet_userneedswallet"`
const idTemplate = "faucet-%d-%d-%s"
type Faucet struct {
*storage.Base
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"`
}
@@ -48,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)
@@ -61,10 +67,10 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
if err != nil {
return nil, errors.New(errors.InvalidAmountError, err)
}
if perUserAmount < 1 || amount%perUserAmount != 0 {
if perUserAmount < 5 || amount%perUserAmount != 0 {
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("invalid amount per user"))
}
nTotal := amount / perUserAmount
nTotal := int(amount / perUserAmount)
fromUser := LoadUser(ctx)
fromUserStr := GetUserStr(sender)
balance, err := bot.GetUserBalanceCached(fromUser)
@@ -73,7 +79,7 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
}
// check if fromUser has balance
if balance < amount {
return nil, errors.New(errors.BalanceToLowError, fmt.Errorf("[faucet] Balance of user %s too low: %v", fromUserStr, err))
return nil, errors.New(errors.BalanceToLowError, fmt.Errorf("[faucet] Balance of user %s too low", fromUserStr))
}
// // check for memo in command
memo := GetMemoFromCommand(text, 3)
@@ -82,10 +88,14 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
if len(memo) > 0 {
inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineFaucetAppendMemo"), memo)
}
id := fmt.Sprintf("inl-faucet-%d-%d-%s", sender.ID, amount, RandStringRunes(5))
return &InlineFaucet{
Base: transaction.New(transaction.ID(id)),
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,
From: fromUser,
@@ -99,66 +109,62 @@ 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 context.Context, q *tb.Query, query bool) (*InlineFaucet, error) {
faucet, err := bot.createFaucet(ctx, q.Text, &q.From)
if err != nil {
switch err.(errors.TipBotError).Code {
case errors.DecodeAmountError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.DecodePerUserAmountError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.InvalidAmountError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.InvalidAmountPerUserError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineFaucetInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.GetBalanceError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.BalanceToLowError:
log.Errorf(err.Error())
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
}
}
return faucet, err
}
func (bot TipBot) makeFaucetKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
@@ -175,16 +181,16 @@ func (bot TipBot) makeFaucetKeyboard(ctx context.Context, id string) *tb.ReplyMa
return inlineFaucetMenu
}
func (bot TipBot) faucetHandler(ctx context.Context, m *tb.Message) {
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 = bot.mapFaucetLanguage(ctx, m.Text)
inlineFaucet, err := bot.makeFaucet(ctx, m, false)
inlineFaucet, err := bot.createFaucet(ctx, m.Text, false, m.Sender)
if err != nil {
log.Errorf("[faucet] %s", err)
log.Warnf("[faucet] %s", err.Error())
return
}
fromUserStr := GetUserStr(m.Sender)
@@ -193,10 +199,11 @@ func (bot TipBot) faucetHandler(ctx context.Context, m *tb.Message) {
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
}
func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
inlineFaucet, err := bot.makeQueryFaucet(ctx, q, false)
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("[faucet] %s", err)
bot.handleFaucetError(ctx, q, err)
log.Errorf("[createInlineFaucetHandler] %s", err.Error())
return
}
urls := []string{
@@ -218,7 +225,7 @@ func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
results[i].SetResultID(inlineFaucet.ID)
bot.Cache.Set(inlineFaucet.ID, inlineFaucet, &store.Options{Expiration: 5 * time.Minute})
log.Infof("[faucet] %s created inline faucet %s: %d sat (%d per user)", GetUserStr(inlineFaucet.From.Telegram), inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
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(q, &tb.QueryResponse{
@@ -226,33 +233,35 @@ func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
CacheTime: 1,
})
if err != nil {
log.Errorln(err)
log.Errorln(err.Error())
}
}
func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) acceptFaucetHandler(ctx context.Context, c *tb.Callback) {
to := LoadUser(ctx)
tx := &InlineFaucet{Base: transaction.New(transaction.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("[faucet] %s", err)
log.Debugf("[acceptFaucetHandler] %s", err.Error())
return
}
inlineFaucet := fn.(*InlineFaucet)
inlineFaucet := fn.(*Faucet)
from := inlineFaucet.From
err = inlineFaucet.Lock(inlineFaucet, bot.Bunt)
if err != nil {
log.Errorf("[faucet] LockFaucet %s error: %s", inlineFaucet.ID, err)
return
// log faucet link if possible
if c.Message != nil && c.Message.Chat != nil {
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.Errorf(fmt.Sprintf("[faucet] faucet %s inactive.", inlineFaucet.ID))
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
defer inlineFaucet.Release(inlineFaucet, bot.Bunt)
if from.Telegram.ID == to.Telegram.ID {
log.Debugf("[faucet] %s is the owner faucet %s", GetUserStr(to.Telegram), inlineFaucet.ID)
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
return
}
@@ -260,11 +269,13 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
for _, a := range inlineFaucet.To {
if a.Telegram.ID == to.Telegram.ID {
// to user is already in To slice, has taken from facuet
// log.Infof("[faucet] %s already took from faucet %s", GetUserStr(to.Telegram), inlineFaucet.ID)
log.Debugf("[faucet] %s:%d already took from faucet %s", GetUserStr(to.Telegram), to.Telegram.ID, inlineFaucet.ID)
return
}
}
defer inlineFaucet.Set(inlineFaucet, bot.Bunt)
if inlineFaucet.RemainingAmount >= inlineFaucet.PerUserAmount {
toUserStrMd := GetUserStrMd(to.Telegram)
fromUserStrMd := GetUserStrMd(from.Telegram)
@@ -273,7 +284,6 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
// check if user exists and create a wallet if not
_, exists := bot.UserExists(to.Telegram)
if !exists {
log.Infof("[faucet] User %s has no wallet.", toUserStr)
to, err = bot.CreateWalletForTelegramUser(to.Telegram)
if err != nil {
errmsg := fmt.Errorf("[faucet] Error: Could not create wallet for %s", toUserStr)
@@ -294,22 +304,27 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
success, err := t.Send()
if !success {
bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
errMsg := fmt.Sprintf("[faucet] Transaction failed: %s", err)
log.Errorln(errMsg)
errMsg := fmt.Sprintf("[faucet] Transaction failed: %s", err.Error())
log.Warnln(errMsg)
// 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
return
}
log.Infof("[💸 faucet] Faucet %s from %s to %s (%d sat).", inlineFaucet.ID, fromUserStr, toUserStr, inlineFaucet.PerUserAmount)
log.Infof("[💸 faucet] Faucet %s from %s to %s:%d (%d sat).", inlineFaucet.ID, fromUserStr, toUserStr, to.Telegram.ID, inlineFaucet.PerUserAmount)
inlineFaucet.NTaken += 1
inlineFaucet.To = append(inlineFaucet.To, to)
inlineFaucet.RemainingAmount = inlineFaucet.RemainingAmount - inlineFaucet.PerUserAmount
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineFaucetReceivedMessage"), fromUserStrMd, inlineFaucet.PerUserAmount))
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineFaucetSentMessage"), inlineFaucet.PerUserAmount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[faucet] Error: Send message to %s: %s", toUserStr, err)
log.Warnln(errmsg)
}
go func() {
_, 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, inlineFaucet.RemainingAmount, inlineFaucet.Amount, inlineFaucet.NTaken, inlineFaucet.NTotal, MakeProgressbar(inlineFaucet.RemainingAmount, inlineFaucet.Amount))
@@ -322,34 +337,56 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
}
// update message
log.Infoln(inlineFaucet.Message)
bot.tryEditMessage(c.Message, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
// update the message if the faucet still has some sats left after this tx
if inlineFaucet.RemainingAmount >= inlineFaucet.PerUserAmount {
go func() {
bot.tryEditMessage(c.Message, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
}()
}
}
if inlineFaucet.RemainingAmount < inlineFaucet.PerUserAmount {
// faucet is depleted
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetEndedMessage"), inlineFaucet.Amount, inlineFaucet.NTaken)
if inlineFaucet.UserNeedsWallet {
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
}
bot.tryEditMessage(c.Message, inlineFaucet.Message)
inlineFaucet.Active = false
bot.finishFaucet(ctx, c, inlineFaucet)
}
}
func (bot *TipBot) cancelInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
tx := &InlineFaucet{Base: transaction.New(transaction.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.Errorf("[cancelInlineSendHandler] %s", err)
log.Debugf("[cancelInlineFaucetHandler] %s", err.Error())
return
}
inlineFaucet := fn.(*InlineFaucet)
if c.Sender.ID == inlineFaucet.From.Telegram.ID {
inlineFaucet := fn.(*Faucet)
if ignoreID || c.Sender.ID == inlineFaucet.From.Telegram.ID {
bot.tryEditMessage(c.Message, i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage"), &tb.ReplyMarkup{})
// set the inlineFaucet inactive
inlineFaucet.Active = false
inlineFaucet.InTransaction = false
inlineFaucet.Canceled = true
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
log.Debugf("[faucet] Faucet %s canceled.", inlineFaucet.ID)
once.Remove(inlineFaucet.ID)
}
return
}
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.tryEditMessage(c.Message, inlineFaucet.Message, &tb.ReplyMarkup{})
inlineFaucet.Active = false
log.Debugf("[faucet] Faucet finished %s", inlineFaucet.ID)
once.Remove(inlineFaucet.ID)
}
func (bot *TipBot) cancelInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
bot.cancelInlineFaucet(ctx, c, false)
return
}
+4 -2
View File
@@ -95,12 +95,14 @@ func (bot TipBot) inlineQueryReplyWithError(q *tb.Query, message string, help st
}
}
// 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(q *tb.ChosenInlineResult) {
// load inline object from cache
inlineObject, err := bot.Cache.Get(q.ResultID)
// check error
if err != nil {
log.Errorf("[anyChosenInlineHandler] could not find inline object in cache. %v", err)
log.Errorf("[anyChosenInlineHandler] could not find inline object in cache. %v", err.Error())
return
}
switch inlineObject.(type) {
@@ -150,7 +152,7 @@ func (bot TipBot) anyQueryHandler(ctx context.Context, q *tb.Query) {
c := strings.Split(q.Text, " ")[0]
ctx = bot.commandTranslationMap(ctx, c)
}
bot.handleInlineFaucetQuery(ctx, q)
bot.createInlineFaucetHandler(ctx, q)
}
if strings.HasPrefix(q.Text, "tipjar") || strings.HasPrefix(q.Text, "spendendose") {
if len(strings.Split(q.Text, " ")) > 1 {
+137 -35
View File
@@ -1,16 +1,20 @@
package telegram
import (
"bytes"
"context"
"fmt"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/eko/gocache/store"
"github.com/skip2/go-qrcode"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
log "github.com/sirupsen/logrus"
@@ -24,9 +28,10 @@ var (
)
type InlineReceive struct {
*transaction.Base
Message string `json:"inline_receive_message"`
Amount int `json:"inline_receive_amount"`
*storage.Base
MessageText string `json:"inline_receive_messagetext"`
Message *tb.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"`
From_SpecificUser bool `json:"from_specific_user"`
@@ -41,8 +46,9 @@ func (bot TipBot) makeReceiveKeyboard(ctx context.Context, id string) *tb.ReplyM
cancelInlineReceiveButton.Data = id
inlineReceiveMenu.Inline(
inlineReceiveMenu.Row(
cancelInlineReceiveButton,
acceptInlineReceiveButton,
cancelInlineReceiveButton),
),
)
return inlineReceiveMenu
}
@@ -115,8 +121,8 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
results[i].SetResultID(id)
// create persistend inline send struct
inlineReceive := InlineReceive{
Base: transaction.New(transaction.ID(id)),
Message: inlineMessage,
Base: storage.New(storage.ID(id)),
MessageText: inlineMessage,
To: to,
Memo: memo,
Amount: amount,
@@ -138,33 +144,24 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
}
func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
tx := &InlineReceive{Base: transaction.New(transaction.ID(c.Data))}
rn, err := tx.Get(tx, bot.Bunt)
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
// immediatelly set intransaction to block duplicate calls
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
rn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[getInlineReceive] %s", err)
log.Errorf("[getInlineReceive] %s", err.Error())
return
}
inlineReceive := rn.(*InlineReceive)
err = inlineReceive.Lock(inlineReceive, bot.Bunt)
if err != nil {
log.Errorf("[acceptInlineReceiveHandler] %s", err)
return
}
if !inlineReceive.Active {
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
return
}
defer inlineReceive.Release(inlineReceive, bot.Bunt)
// user `from` is the one who is SENDING
// user `to` is the one who is RECEIVING
from := LoadUser(ctx)
if from.Wallet == nil {
return
}
// check if this payment is requested from a specific user
if inlineReceive.From_SpecificUser {
if inlineReceive.From.Telegram.ID != from.Telegram.ID {
@@ -174,18 +171,60 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callbac
} else {
// otherwise, we just set it to the user who has clicked
inlineReceive.From = from
}
inlineReceive.Message = c.Message
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
to := inlineReceive.To
toUserStrMd := GetUserStrMd(to.Telegram)
fromUserStrMd := GetUserStrMd(from.Telegram)
toUserStr := GetUserStr(to.Telegram)
fromUserStr := GetUserStr(from.Telegram)
if from.Telegram.ID == to.Telegram.ID {
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
return
}
balance, err := bot.GetUserBalance(from)
if err != nil {
errmsg := fmt.Sprintf("[inlineReceive] Error: Could not get user balance: %s", err.Error())
log.Warnln(errmsg)
}
if from.Wallet == nil || balance < inlineReceive.Amount {
// if user has no wallet, show invoice
bot.tryEditMessage(inlineReceive.Message, inlineReceive.MessageText, &tb.ReplyMarkup{})
// runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
bot.inlineReceiveInvoice(ctx, c, inlineReceive)
return
} else {
// else, do an internal transaction
bot.sendInlineReceiveHandler(ctx, c)
return
}
}
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)
rn, err := tx.Get(tx, bot.Bunt)
// immediatelly set intransaction to block duplicate calls
if err != nil {
// log.Errorf("[getInlineReceive] %s", err.Error())
return
}
inlineReceive := rn.(*InlineReceive)
if !inlineReceive.Active {
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
return
}
// defer inlineReceive.Release(inlineReceive, bot.Bunt)
// from := inlineReceive.From
from := LoadUser(ctx)
to := inlineReceive.To
toUserStr := GetUserStr(to.Telegram)
fromUserStr := GetUserStr(from.Telegram)
// balance check of the user
balance, err := bot.GetUserBalanceCached(from)
if err != nil {
@@ -209,25 +248,86 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callbac
t.Memo = transactionMemo
success, err := t.Send()
if !success {
errMsg := fmt.Sprintf("[acceptInlineReceiveHandler] Transaction failed: %s", err)
errMsg := fmt.Sprintf("[acceptInlineReceiveHandler] Transaction failed: %s", err.Error())
log.Errorln(errMsg)
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveFailedMessage"), &tb.ReplyMarkup{})
return
}
log.Infof("[💸 inlineReceive] Send from %s to %s (%d sat).", fromUserStr, toUserStr, inlineReceive.Amount)
inlineReceive.Set(inlineReceive, bot.Bunt)
bot.finishInlineReceiveHandler(ctx, c)
}
inlineReceive.Message = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendUpdateMessageAccept"), inlineReceive.Amount, fromUserStrMd, toUserStrMd))
func (bot *TipBot) inlineReceiveInvoice(ctx context.Context, c *tb.Callback, inlineReceive *InlineReceive) {
if !inlineReceive.Active {
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
return
}
invoice, err := bot.createInvoiceWithEvent(ctx, inlineReceive.To, inlineReceive.Amount, fmt.Sprintf("Pay to %s", GetUserStr(inlineReceive.To.Telegram)), InvoiceCallbackInlineReceive, inlineReceive.ID)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
bot.tryEditMessage(inlineReceive.Message, Translate(ctx, "errorTryLaterMessage"))
log.Errorln(errmsg)
return
}
// create qr code
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
bot.tryEditMessage(inlineReceive.Message, Translate(ctx, "errorTryLaterMessage"))
log.Errorln(errmsg)
return
}
// send the invoice data to user
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(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) {
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
// immediatelly set intransaction to block duplicate calls
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
rn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[getInlineReceive] %s", err.Error())
return
}
inlineReceive := rn.(*InlineReceive)
from := inlineReceive.From
to := inlineReceive.To
toUserStrMd := GetUserStrMd(to.Telegram)
fromUserStrMd := GetUserStrMd(from.Telegram)
toUserStr := GetUserStr(to.Telegram)
inlineReceive.MessageText = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendUpdateMessageAccept"), inlineReceive.Amount, fromUserStrMd, toUserStrMd))
memo := inlineReceive.Memo
if len(memo) > 0 {
inlineReceive.Message = inlineReceive.Message + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveAppendMemo"), memo)
inlineReceive.MessageText += fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveAppendMemo"), memo)
}
if !to.Initialized {
inlineReceive.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
inlineReceive.MessageText += "\n\n" + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
}
bot.tryEditMessage(c.Message, inlineReceive.Message, &tb.ReplyMarkup{})
bot.tryEditMessage(inlineReceive.Message, inlineReceive.MessageText, &tb.ReplyMarkup{})
// notify users
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, inlineReceive.Amount))
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), inlineReceive.Amount, toUserStrMd))
@@ -235,14 +335,17 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callbac
errmsg := fmt.Errorf("[acceptInlineReceiveHandler] Error: Receive message to %s: %s", toUserStr, err)
log.Warnln(errmsg)
}
// inlineReceive.Release(inlineReceive, bot.Bunt)
}
func (bot *TipBot) cancelInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
tx := &InlineReceive{Base: transaction.New(transaction.ID(c.Data))}
rn, err := tx.Get(tx, bot.Bunt)
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
// immediatelly set intransaction to block duplicate calls
rn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[cancelInlineReceiveHandler] %s", err)
log.Errorf("[cancelInlineReceiveHandler] %s", err.Error())
return
}
inlineReceive := rn.(*InlineReceive)
@@ -250,7 +353,6 @@ func (bot *TipBot) cancelInlineReceiveHandler(ctx context.Context, c *tb.Callbac
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveCancelledMessage"), &tb.ReplyMarkup{})
// set the inlineReceive inactive
inlineReceive.Active = false
inlineReceive.InTransaction = false
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
}
return
+17 -18
View File
@@ -6,12 +6,14 @@ import (
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/eko/gocache/store"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
log "github.com/sirupsen/logrus"
@@ -25,9 +27,9 @@ var (
)
type InlineSend struct {
*transaction.Base
*storage.Base
Message string `json:"inline_send_message"`
Amount int `json:"inline_send_amount"`
Amount int64 `json:"inline_send_amount"`
From *lnbits.User `json:"inline_send_from"`
To *lnbits.User `json:"inline_send_to"`
To_SpecificUser bool `json:"to_specific_user"`
@@ -132,7 +134,7 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
// add data to persistent object
inlineSend := InlineSend{
Base: transaction.New(transaction.ID(id)),
Base: storage.New(storage.ID(id)),
Message: inlineMessage,
From: fromUser,
To: toUserDb,
@@ -158,28 +160,24 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback) {
to := LoadUser(ctx)
tx := &InlineSend{Base: transaction.New(transaction.ID(c.Data))}
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.Bunt)
// immediatelly set intransaction to block duplicate calls
if err != nil {
log.Errorf("[acceptInlineSendHandler] %s", err)
// log.Errorf("[acceptInlineSendHandler] %s", err.Error())
return
}
inlineSend := sn.(*InlineSend)
fromUser := inlineSend.From
// immediatelly set intransaction to block duplicate calls
err = inlineSend.Lock(inlineSend, bot.Bunt)
if err != nil {
log.Errorf("[getInlineSend] %s", err)
return
}
if !inlineSend.Active {
log.Errorf("[acceptInlineSendHandler] inline send not active anymore")
return
}
defer inlineSend.Release(inlineSend, bot.Bunt)
defer inlineSend.Set(inlineSend, bot.Bunt)
amount := inlineSend.Amount
@@ -224,7 +222,7 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
t.Memo = transactionMemo
success, err := t.Send()
if !success {
errMsg := fmt.Sprintf("[sendInline] Transaction failed: %s", err)
errMsg := fmt.Sprintf("[sendInline] Transaction failed: %s", err.Error())
log.Errorln(errMsg)
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "inlineSendFailedMessage"), &tb.ReplyMarkup{})
return
@@ -251,11 +249,13 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
}
func (bot *TipBot) cancelInlineSendHandler(ctx context.Context, c *tb.Callback) {
tx := &InlineSend{Base: transaction.New(transaction.ID(c.Data))}
sn, err := tx.Get(tx, bot.Bunt)
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
// immediatelly set intransaction to block duplicate calls
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[cancelInlineSendHandler] %s", err)
log.Errorf("[cancelInlineSendHandler] %s", err.Error())
return
}
inlineSend := sn.(*InlineSend)
@@ -263,7 +263,6 @@ func (bot *TipBot) cancelInlineSendHandler(ctx context.Context, c *tb.Callback)
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
// set the inlineSend inactive
inlineSend.Active = false
inlineSend.InTransaction = false
runtime.IgnoreError(inlineSend.Set(inlineSend, bot.Bunt))
}
return
+23 -25
View File
@@ -6,12 +6,14 @@ import (
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/eko/gocache/store"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
log "github.com/sirupsen/logrus"
@@ -25,11 +27,11 @@ var (
)
type InlineTipjar struct {
*transaction.Base
*storage.Base
Message string `json:"inline_tipjar_message"`
Amount int `json:"inline_tipjar_amount"`
GivenAmount int `json:"inline_tipjar_givenamount"`
PerUserAmount int `json:"inline_tipjar_peruseramount"`
Amount int64 `json:"inline_tipjar_amount"`
GivenAmount int64 `json:"inline_tipjar_givenamount"`
PerUserAmount int64 `json:"inline_tipjar_peruseramount"`
To *lnbits.User `json:"inline_tipjar_to"`
From []*lnbits.User `json:"inline_tipjar_from"`
Memo string `json:"inline_tipjar_memo"`
@@ -62,7 +64,7 @@ func (bot TipBot) createTipjar(ctx context.Context, text string, sender *tb.User
if perUserAmount < 1 || amount%perUserAmount != 0 {
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("invalid amount per user"))
}
nTotal := amount / perUserAmount
nTotal := int(amount / perUserAmount)
toUser := LoadUser(ctx)
// toUserStr := GetUserStr(sender)
// // check for memo in command
@@ -83,7 +85,7 @@ func (bot TipBot) createTipjar(ctx context.Context, text string, sender *tb.User
id := fmt.Sprintf("inl-tipjar-%d-%d-%s", sender.ID, amount, RandStringRunes(5))
return &InlineTipjar{
Base: transaction.New(transaction.ID(id)),
Base: storage.New(storage.ID(id)),
Message: inlineMessage,
Amount: amount,
To: toUser,
@@ -162,10 +164,10 @@ func (bot TipBot) makeTipjarKeyboard(ctx context.Context, inlineTipjar *InlineTi
// inlineTipjarMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
// slice of buttons
buttons := make([]tb.Btn, 0)
acceptInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "payReceiveButtonMessage"), "confirm_tipjar_inline", inlineTipjar.ID)
buttons = append(buttons, acceptInlineTipjarButton)
cancelInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_tipjar_inline", inlineTipjar.ID)
buttons = append(buttons, cancelInlineTipjarButton)
acceptInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "payReceiveButtonMessage"), "confirm_tipjar_inline", inlineTipjar.ID)
buttons = append(buttons, acceptInlineTipjarButton)
inlineTipjarMenu.Inline(
inlineTipjarMenu.Row(buttons...))
@@ -181,7 +183,7 @@ func (bot TipBot) tipjarHandler(ctx context.Context, m *tb.Message) {
ctx = bot.mapTipjarLanguage(ctx, m.Text)
inlineTipjar, err := bot.makeTipjar(ctx, m, false)
if err != nil {
log.Errorf("[tipjar] %s", err)
log.Errorf("[tipjar] %s", err.Error())
return
}
toUserStr := GetUserStr(m.Sender)
@@ -193,7 +195,7 @@ func (bot TipBot) tipjarHandler(ctx context.Context, m *tb.Message) {
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)
// log.Errorf("[tipjar] %s", err.Error())
return
}
urls := []string{
@@ -233,25 +235,20 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
if from.Wallet == nil {
return
}
tx := &InlineTipjar{Base: transaction.New(transaction.ID(c.Data))}
tx := &InlineTipjar{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[tipjar] %s", err)
// log.Errorf("[tipjar] %s", err.Error())
return
}
inlineTipjar := fn.(*InlineTipjar)
to := inlineTipjar.To
err = inlineTipjar.Lock(inlineTipjar, bot.Bunt)
if err != nil {
log.Errorf("[tipjar] LockTipjar %s error: %s", inlineTipjar.ID, err)
return
}
if !inlineTipjar.Active {
log.Errorf(fmt.Sprintf("[tipjar] tipjar %s inactive.", inlineTipjar.ID))
return
}
// release tipjar no matter what
defer inlineTipjar.Release(inlineTipjar, bot.Bunt)
if from.Telegram.ID == to.Telegram.ID {
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
@@ -259,7 +256,7 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
}
// // check if to user has already given to the tipjar
for _, a := range inlineTipjar.From {
if a.Telegram.ID == to.Telegram.ID {
if a.Telegram.ID == from.Telegram.ID {
// to user is already in To slice, has taken from facuet
// log.Infof("[tipjar] %s already gave to tipjar %s", GetUserStr(to.Telegram), inlineTipjar.ID)
return
@@ -279,7 +276,7 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
success, err := t.Send()
if !success {
bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
errMsg := fmt.Sprintf("[tipjar] Transaction failed: %s", err)
errMsg := fmt.Sprintf("[tipjar] Transaction failed: %s", err.Error())
log.Errorln(errMsg)
return
}
@@ -335,10 +332,12 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
}
func (bot *TipBot) cancelInlineTipjarHandler(ctx context.Context, c *tb.Callback) {
tx := &InlineTipjar{Base: transaction.New(transaction.ID(c.Data))}
tx := &InlineTipjar{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[cancelInlineSendHandler] %s", err)
log.Errorf("[cancelInlineTipjarHandler] %s", err.Error())
return
}
inlineTipjar := fn.(*InlineTipjar)
@@ -346,7 +345,6 @@ func (bot *TipBot) cancelInlineTipjarHandler(ctx context.Context, c *tb.Callback
bot.tryEditMessage(c.Message, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
// set the inlineTipjar inactive
inlineTipjar.Active = false
inlineTipjar.InTransaction = false
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
}
return
+9 -1
View File
@@ -13,6 +13,7 @@ type handlerCallbackInterceptor struct {
handler CallbackFuncHandler
before CallbackChain
after CallbackChain
onDefer CallbackChain
}
type CallbackChain []Func
type CallbackInterceptOption func(*handlerCallbackInterceptor)
@@ -27,6 +28,11 @@ func WithAfterCallback(chain ...Func) CallbackInterceptOption {
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 {
@@ -50,11 +56,13 @@ func HandlerWithCallback(handler CallbackFuncHandler, option ...CallbackIntercep
opt(hm)
}
return func(c *tb.Callback) {
ctx, err := interceptCallback(context.Background(), c, hm.before)
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 {
+9 -2
View File
@@ -16,6 +16,7 @@ type handlerMessageInterceptor struct {
handler MessageFuncHandler
before MessageChain
after MessageChain
onDefer MessageChain
}
type MessageChain []Func
type MessageInterceptOption func(*handlerMessageInterceptor)
@@ -30,6 +31,11 @@ func WithAfterMessage(chain ...Func) MessageInterceptOption {
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 {
@@ -48,17 +54,18 @@ func interceptMessage(ctx context.Context, message *tb.Message, hm MessageChain)
}
func HandlerWithMessage(handler MessageFuncHandler, option ...MessageInterceptOption) func(message *tb.Message) {
hm := &handlerMessageInterceptor{handler: handler}
for _, opt := range option {
opt(hm)
}
return func(message *tb.Message) {
ctx, err := interceptMessage(context.Background(), message, hm.before)
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 {
+12 -4
View File
@@ -13,6 +13,7 @@ type handlerQueryInterceptor struct {
handler QueryFuncHandler
before QueryChain
after QueryChain
onDefer QueryChain
}
type QueryChain []Func
type QueryInterceptOption func(*handlerQueryInterceptor)
@@ -27,6 +28,11 @@ func WithAfterQuery(chain ...Func) QueryInterceptOption {
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 {
@@ -49,14 +55,16 @@ func HandlerWithQuery(handler QueryFuncHandler, option ...QueryInterceptOption)
for _, opt := range option {
opt(hm)
}
return func(message *tb.Query) {
ctx, err := interceptQuery(context.Background(), message, hm.before)
return func(query *tb.Query) {
ctx := context.Background()
ctx, err := interceptQuery(context.Background(), query, hm.before)
if err != nil {
log.Traceln(err)
return
}
hm.handler(ctx, message)
_, err = interceptQuery(ctx, message, hm.after)
defer interceptQuery(ctx, query, hm.onDefer)
hm.handler(ctx, query)
_, err = interceptQuery(ctx, query, hm.after)
if err != nil {
log.Traceln(err)
return
+83 -15
View File
@@ -3,6 +3,11 @@ package telegram
import (
"context"
"fmt"
"reflect"
"strconv"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/once"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
i18n2 "github.com/nicksnyder/go-i18n/v2/i18n"
@@ -24,33 +29,96 @@ const (
var invalidTypeError = fmt.Errorf("invalid type")
type Interceptor struct {
Type InterceptorType
Before []intercept.Func
After []intercept.Func
Type InterceptorType
Before []intercept.Func
After []intercept.Func
OnDefer []intercept.Func
}
func (bot TipBot) requireUserInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
// 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 context.Context, i interface{}) (context.Context, error) {
switch i.(type) {
case *tb.Query:
user, err := GetUser(&i.(*tb.Query).From, bot)
return context.WithValue(ctx, "user", user), err
case *tb.Callback:
c := i.(*tb.Callback)
m := *c.Message
m.Sender = c.Sender
user, err := GetUser(i.(*tb.Callback).Sender, bot)
return context.WithValue(ctx, "user", user), err
case *tb.Message:
user, err := GetUser(i.(*tb.Message).Sender, bot)
return context.WithValue(ctx, "user", user), err
return ctx, once.Once(c.Data, strconv.FormatInt(c.Sender.ID, 10))
}
return ctx, invalidTypeError
}
// unlockInterceptor invoked as onDefer interceptor
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, invalidTypeError
}
func (bot TipBot) idInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
return context.WithValue(ctx, "uid", RandStringRunes(64)), nil
}
func (bot TipBot) answerCallbackInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
switch i.(type) {
case *tb.Callback:
c := i.(*tb.Callback)
ctxcr := ctx.Value("callback_response")
var res []*tb.CallbackResponse
if ctxcr != nil {
res = append(res, &tb.CallbackResponse{CallbackID: c.ID, Text: ctxcr.(string)})
}
var err error
err = bot.Telegram.Respond(c, res...)
return ctx, err
}
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 context.Context, i interface{}) (context.Context, error) {
var user *lnbits.User
var err error
u := getTelegramUserFromInterface(i)
if u != nil {
user, err = GetUser(u, bot)
if user != nil {
return context.WithValue(ctx, "user", user), err
}
}
return nil, invalidTypeError
}
func (bot TipBot) loadUserInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
ctx, _ = bot.requireUserInterceptor(ctx, i)
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) {
@@ -108,7 +176,7 @@ func (bot TipBot) requirePrivateChatInterceptor(ctx context.Context, i interface
case *tb.Message:
m := i.(*tb.Message)
if m.Chat.Type != tb.ChatPrivate {
return nil, fmt.Errorf("no private chat")
return nil, fmt.Errorf("[requirePrivateChatInterceptor] no private chat")
}
return ctx, nil
}
+108 -12
View File
@@ -5,16 +5,60 @@ import (
"context"
"fmt"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/skip2/go-qrcode"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type InvoiceEventCallback map[int]func(*InvoiceEvent)
var InvoiceCallback InvoiceEventCallback
func initInvoiceEventCallbacks(bot *TipBot) {
InvoiceCallback = InvoiceEventCallback{
InvoiceCallbackGeneric: bot.notifyInvoiceReceivedEvent,
InvoiceCallbackInlineReceive: bot.inlineReceiveEvent,
InvoiceCallbackLNURLPayReceive: bot.lnurlReceiveEvent,
}
}
type InvoiceEventKey int
const (
InvoiceCallbackGeneric = iota + 1
InvoiceCallbackInlineReceive
InvoiceCallbackLNURLPayReceive
)
type Invoice struct {
PaymentHash string `json:"payment_hash"`
PaymentRequest string `json:"payment_request"`
Amount int64 `json:"amount"`
Memo string `json:"memo"`
}
type InvoiceEvent struct {
*Invoice
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 {
return fmt.Sprintf("invoice:%s", invoiceEvent.PaymentHash)
}
func helpInvoiceUsage(ctx context.Context, errormsg string) string {
if len(errormsg) > 0 {
return fmt.Sprintf(Translate(ctx, "invoiceHelpText"), fmt.Sprintf("%s", errormsg))
@@ -23,7 +67,7 @@ func helpInvoiceUsage(ctx context.Context, errormsg string) string {
}
}
func (bot TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
// check and print all commands
bot.anyTextHandler(ctx, m)
user := LoadUser(ctx)
@@ -58,16 +102,9 @@ func (bot TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
creatingMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
log.Infof("[/invoice] Creating invoice for %s of %d sat.", userStr, amount)
// generate invoice
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Out: false,
Amount: int64(amount),
Memo: memo,
Webhook: internal.Configuration.Lnbits.WebhookServer},
bot.Client)
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, InvoiceCallbackGeneric, "")
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err)
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
log.Errorln(errmsg)
return
@@ -76,15 +113,74 @@ func (bot TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
// 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)
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
log.Errorln(errmsg)
return
}
bot.tryDeleteMessage(creatingMsg)
// deleting messages will delete the main menu.
//bot.tryDeleteMessage(creatingMsg)
// send the invoice data to user
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
log.Printf("[/invoice] Incvoice created. User: %s, amount: %d sat.", userStr, amount)
return
}
func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User, amount int64, memo string, callback int, callbackData string) (InvoiceEvent, error) {
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Out: false,
Amount: int64(amount),
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
}
invoiceEvent := InvoiceEvent{
Invoice: &Invoice{PaymentHash: invoice.PaymentHash,
PaymentRequest: invoice.PaymentRequest,
Amount: amount,
Memo: memo},
User: user,
Callback: callback,
CallbackData: callbackData,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
// save invoice struct for later use
runtime.IgnoreError(bot.Bunt.Set(invoiceEvent))
return invoiceEvent, nil
}
func (bot *TipBot) notifyInvoiceReceivedEvent(invoiceEvent *InvoiceEvent) {
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
}
type LNURLInvoice struct {
*Invoice
Comment string `json:"comment"`
User *lnbits.User `json:"user"`
CreatedAt time.Time `json:"created_at"`
Paid bool `json:"paid"`
PaidAt time.Time `json:"paid_at"`
}
func (lnurlInvoice LNURLInvoice) Key() string {
return fmt.Sprintf("lnurl-p:%s", lnurlInvoice.PaymentHash)
}
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 {
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf(`✉️ %s`, str.MarkdownEscape(tx.Comment)))
}
}
}
+6 -3
View File
@@ -40,15 +40,18 @@ func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
// create qr code
qr, err := qrcode.Encode(lndhubUrl, qrcode.Medium, 256)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err)
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
log.Errorln(errmsg)
return
}
// send the link to the user
linkmsg := bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
time.Sleep(time.Second * 60)
bot.tryDeleteMessage(linkmsg)
go func() {
time.Sleep(time.Second * 60)
bot.tryDeleteMessage(linkmsg)
}()
bot.trySendMessage(m.Sender, Translate(ctx, "linkHiddenMessage"))
// auto delete the message
// NewMessage(linkmsg, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
+13 -8
View File
@@ -9,9 +9,12 @@ import (
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
lnurl "github.com/fiatjaf/go-lnurl"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
@@ -19,11 +22,11 @@ import (
// LnurlPayState saves the state of the user for an LNURL payment
type LnurlPayState struct {
*transaction.Base
*storage.Base
From *lnbits.User `json:"from"`
LNURLPayParams lnurl.LNURLPayParams `json:"LNURLPayParams"`
LNURLPayValues lnurl.LNURLPayValues `json:"LNURLPayValues"`
Amount int `json:"amount"`
Amount int64 `json:"amount"`
Comment string `json:"comment"`
LanguageCode string `json:"languagecode"`
}
@@ -37,8 +40,8 @@ func (bot *TipBot) lnurlPayHandler(ctx context.Context, m *tb.Message, payParams
}
// object that holds all information about the send payment
id := fmt.Sprintf("lnurlp-%d-%s", m.Sender.ID, RandStringRunes(5))
lnurlPayState := LnurlPayState{
Base: transaction.New(transaction.ID(id)),
lnurlPayState := &LnurlPayState{
Base: storage.New(storage.ID(id)),
From: user,
LNURLPayParams: payParams.LNURLPayParams,
LanguageCode: ctx.Value("publicLanguageCode").(string),
@@ -126,7 +129,9 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
}
// use the enter amount state of the user to load the LNURL payment state
tx := &LnurlPayState{Base: transaction.New(transaction.ID(enterAmountData.ID))}
tx := &LnurlPayState{Base: storage.New(storage.ID(enterAmountData.ID))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
@@ -151,7 +156,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
}
qs := callbackUrl.Query()
// add amount to query string
qs.Set("amount", strconv.Itoa(lnurlPayState.Amount)) // msat
qs.Set("amount", strconv.FormatInt(lnurlPayState.Amount, 10)) // msat
// add comment to query string
if len(lnurlPayState.Comment) > 0 {
qs.Set("comment", lnurlPayState.Comment)
@@ -192,7 +197,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
bot.payHandler(ctx, m)
}
func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, address string, amount int) error {
func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, address string, amount int64) error {
split := strings.Split(address, "@")
if len(split) != 2 {
return fmt.Errorf("lightning address format wrong")
+20 -19
View File
@@ -7,11 +7,14 @@ import (
"io/ioutil"
"net/url"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
"github.com/LightningTipBot/LightningTipBot/internal/str"
lnurl "github.com/fiatjaf/go-lnurl"
log "github.com/sirupsen/logrus"
@@ -26,11 +29,11 @@ var (
// LnurlWithdrawState saves the state of the user for an LNURL payment
type LnurlWithdrawState struct {
*transaction.Base
*storage.Base
From *lnbits.User `json:"from"`
LNURLWithdrawResponse lnurl.LNURLWithdrawResponse `json:"LNURLWithdrawResponse"`
LNURResponse lnurl.LNURLResponse `json:"LNURLResponse"`
Amount int `json:"amount"`
Amount int64 `json:"amount"`
Comment string `json:"comment"`
LanguageCode string `json:"languagecode"`
Success bool `json:"success"`
@@ -60,7 +63,7 @@ func (bot *TipBot) lnurlWithdrawHandler(ctx context.Context, m *tb.Message, with
// object that holds all information about the send payment
id := fmt.Sprintf("lnurlw-%d-%s", m.Sender.ID, RandStringRunes(5))
LnurlWithdrawState := LnurlWithdrawState{
Base: transaction.New(transaction.ID(id)),
Base: storage.New(storage.ID(id)),
From: user,
LNURLWithdrawResponse: withdrawParams.LNURLWithdrawResponse,
LanguageCode: ctx.Value("publicLanguageCode").(string),
@@ -83,7 +86,7 @@ func (bot *TipBot) lnurlWithdrawHandler(ctx context.Context, m *tb.Message, with
// if no amount is entered, and if only one amount is possible, we use it
if amount_err != nil && LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable == LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable {
amount = int(LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable / 1000)
amount = int64(LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable / 1000)
amount_err = nil
}
@@ -138,7 +141,9 @@ func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Messa
}
// use the enter amount state of the user to load the LNURL payment state
tx := &LnurlWithdrawState{Base: transaction.New(transaction.ID(enterAmountData.ID))}
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(enterAmountData.ID))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
@@ -182,12 +187,15 @@ func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Messa
// confirmPayHandler when user clicked pay on payment confirmation
func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) {
tx := &LnurlWithdrawState{Base: transaction.New(transaction.ID(c.Data))}
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
}
var lnurlWithdrawState *LnurlWithdrawState
switch fn.(type) {
case *LnurlWithdrawState:
@@ -200,21 +208,13 @@ func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) {
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
return
}
// immediatelly set intransaction to block duplicate calls
err = lnurlWithdrawState.Lock(lnurlWithdrawState, bot.Bunt)
if err != nil {
log.Errorf("[confirmWithdrawHandler] %s", err)
bot.tryDeleteMessage(c.Message)
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
return
}
if !lnurlWithdrawState.Active {
log.Errorf("[confirmPayHandler] send not active anymore")
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
bot.tryDeleteMessage(c.Message)
return
}
defer lnurlWithdrawState.Release(lnurlWithdrawState, bot.Bunt)
defer lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt)
user := LoadUser(ctx)
if user.Wallet == nil {
@@ -246,7 +246,7 @@ func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) {
Webhook: internal.Configuration.Lnbits.WebhookServer},
bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[lnurlWithdrawHandlerWithdraw] Could not create an invoice: %s", err)
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
@@ -307,7 +307,9 @@ func (bot *TipBot) cancelWithdrawHandler(ctx context.Context, c *tb.Callback) {
// reset state immediately
user := LoadUser(ctx)
ResetUserState(user, bot)
tx := &LnurlWithdrawState{Base: transaction.New(transaction.ID(c.Data))}
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[cancelWithdrawHandler] Error: %s", err.Error())
@@ -325,6 +327,5 @@ func (bot *TipBot) cancelWithdrawHandler(ctx context.Context, c *tb.Callback) {
return
}
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawCancelled"), &tb.ReplyMarkup{})
lnurlWithdrawState.InTransaction = false
lnurlWithdrawState.Inactivate(lnurlWithdrawState, bot.Bunt)
}
+6 -5
View File
@@ -72,7 +72,8 @@ func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) {
return
}
// assume payment
// get rid of the URI prefix
lnurlSplit = strings.TrimPrefix(lnurlSplit, "lightning:")
// HandleLNURL by fiatjaf/go-lnurl
_, params, err := bot.HandleLNURL(lnurlSplit)
if err != nil {
@@ -82,10 +83,10 @@ func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) {
}
switch params.(type) {
case lnurl.LNURLPayParams:
payParams := LnurlPayState{LNURLPayParams: params.(lnurl.LNURLPayParams)}
payParams := &LnurlPayState{LNURLPayParams: params.(lnurl.LNURLPayParams)}
log.Infof("[LNURL-p] %s", payParams.LNURLPayParams.Callback)
bot.tryDeleteMessage(statusMsg)
bot.lnurlPayHandler(ctx, m, payParams)
bot.lnurlPayHandler(ctx, m, *payParams)
return
case lnurl.LNURLWithdrawResponse:
withdrawParams := LnurlWithdrawState{LNURLWithdrawResponse: params.(lnurl.LNURLWithdrawResponse)}
@@ -140,14 +141,14 @@ 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)
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to get LNURL: %s", err.Error())
log.Errorln(errmsg)
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)
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to create QR code for LNURL: %s", err.Error())
log.Errorln(errmsg)
return
}
+23 -24
View File
@@ -5,10 +5,13 @@ import (
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
"github.com/LightningTipBot/LightningTipBot/internal/str"
decodepay "github.com/fiatjaf/ln-decodepay"
log "github.com/sirupsen/logrus"
@@ -30,7 +33,7 @@ func helpPayInvoiceUsage(ctx context.Context, errormsg string) string {
}
type PayData struct {
*transaction.Base
*storage.Base
From *lnbits.User `json:"from"`
Invoice string `json:"invoice"`
Hash string `json:"hash"`
@@ -60,7 +63,7 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
if err != nil {
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
errmsg := fmt.Sprintf("[/pay] Error: Could not getArgumentFromCommand: %s", err)
errmsg := fmt.Sprintf("[/pay] Error: Could not getArgumentFromCommand: %s", err.Error())
log.Errorln(errmsg)
return
}
@@ -72,11 +75,11 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
bolt11, err := decodepay.Decodepay(paymentRequest)
if err != nil {
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err)
errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err.Error())
log.Errorln(errmsg)
return
}
amount := int(bolt11.MSatoshi / 1000)
amount := int64(bolt11.MSatoshi / 1000)
if amount <= 0 {
bot.trySendMessage(m.Sender, Translate(ctx, "invoiceNoAmountMessage"))
@@ -89,7 +92,7 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
balance, err := bot.GetUserBalance(user)
if err != nil {
NewMessage(m, WithDuration(0, bot))
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err)
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err.Error())
log.Errorln(errmsg)
bot.trySendMessage(m.Sender, Translate(ctx, "errorTryLaterMessage"))
return
@@ -127,8 +130,8 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
cancelButton),
)
payMessage := bot.trySendMessage(m.Chat, confirmText, paymentConfirmationMenu)
payData := PayData{
Base: transaction.New(transaction.ID(id)),
payData := &PayData{
Base: storage.New(storage.ID(id)),
From: user,
Invoice: paymentRequest,
Amount: int64(amount),
@@ -145,11 +148,13 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
// confirmPayHandler when user clicked pay on payment confirmation
func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
tx := &PayData{Base: transaction.New(transaction.ID(c.Data))}
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)
log.Errorf("[confirmPayHandler] %s", err.Error())
return
}
payData := sn.(*PayData)
@@ -158,21 +163,13 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
if payData.From.Telegram.ID != c.Sender.ID {
return
}
// immediatelly set intransaction to block duplicate calls
err = payData.Lock(payData, bot.Bunt)
if err != nil {
log.Errorf("[acceptSendHandler] %s", err)
bot.tryDeleteMessage(c.Message)
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
return
}
if !payData.Active {
log.Errorf("[confirmPayHandler] send not active anymore")
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
bot.tryDeleteMessage(c.Message)
return
}
defer payData.Release(payData, bot.Bunt)
defer payData.Set(payData, bot.Bunt)
// remove buttons from confirmation message
// bot.tryEditMessage(c.Message, MarkdownEscape(payData.Message), &tb.ReplyMarkup{})
@@ -200,6 +197,8 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
},
},
)
log.Infof("[/pay] Attempting %s's invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
// pay invoice
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoiceString}, bot.Client)
if err != nil {
@@ -215,7 +214,6 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
return
}
payData.Hash = invoice.PaymentHash
payData.InTransaction = false
if c.Message.Private() {
// if the command was invoked in private chat
@@ -225,7 +223,7 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
bot.trySendMessage(c.Sender, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePublicPaidMessage"), userStr), &tb.ReplyMarkup{})
}
log.Printf("[⚡️ pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
log.Infof("[⚡️ pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
return
}
@@ -234,9 +232,11 @@ func (bot *TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) {
// reset state immediately
user := LoadUser(ctx)
ResetUserState(user, bot)
tx := &PayData{Base: transaction.New(transaction.ID(c.Data))}
sn, err := tx.Get(tx, bot.Bunt)
tx := &PayData{Base: storage.New(storage.ID(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
@@ -247,6 +247,5 @@ func (bot *TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) {
return
}
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"), &tb.ReplyMarkup{})
payData.InTransaction = false
payData.Inactivate(payData, bot.Bunt)
}
+10 -4
View File
@@ -34,29 +34,35 @@ func TryRecognizeQrCode(img image.Image) (*gozxing.Result, error) {
}
// photoHandler is the handler function for every photo from a private chat that the bot receives
func (bot TipBot) photoHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) photoHandler(ctx context.Context, m *tb.Message) {
if m.Chat.Type != tb.ChatPrivate {
return
}
if m.Photo == nil {
return
}
user := LoadUser(ctx)
if c := stateCallbackMessage[user.StateKey]; c != nil {
c(ctx, m)
ResetUserState(user, bot)
return
}
// get file reader closer from Telegram api
reader, err := bot.Telegram.GetFile(m.Photo.MediaFile())
if err != nil {
log.Errorf("[photoHandler] getfile error: %v\n", err)
log.Errorf("[photoHandler] getfile error: %v\n", err.Error())
return
}
// decode to jpeg image
img, err := jpeg.Decode(reader)
if err != nil {
log.Errorf("[photoHandler] image.Decode error: %v\n", err)
log.Errorf("[photoHandler] image.Decode error: %v\n", err.Error())
return
}
data, err := TryRecognizeQrCode(img)
if err != nil {
log.Errorf("[photoHandler] tryRecognizeQrCodes error: %v\n", err)
log.Errorf("[photoHandler] tryRecognizeQrCodes error: %v\n", err.Error())
bot.trySendMessage(m.Sender, Translate(ctx, "photoQrNotRecognizedMessage"))
return
}
+25 -20
View File
@@ -6,10 +6,13 @@ import (
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
log "github.com/sirupsen/logrus"
@@ -39,7 +42,7 @@ func (bot *TipBot) SendCheckSyntax(ctx context.Context, m *tb.Message) (bool, st
}
type SendData struct {
*transaction.Base
*storage.Base
From *lnbits.User `json:"from"`
ToTelegramId int64 `json:"to_telegram_id"`
ToTelegramUser string `json:"to_telegram_user"`
@@ -159,6 +162,11 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
return
}
if user.ID == toUserDb.ID {
bot.trySendMessage(m.Sender, Translate(ctx, "sendYourselfMessage"))
return
}
// entire text of the inline object
confirmText := fmt.Sprintf(Translate(ctx, "confirmSendMessage"), str.MarkdownEscape(toUserStrMention), amount)
if len(sendMemo) > 0 {
@@ -166,9 +174,9 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
}
// object that holds all information about the send payment
id := fmt.Sprintf("send-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
sendData := SendData{
sendData := &SendData{
From: user,
Base: transaction.New(transaction.ID(id)),
Base: storage.New(storage.ID(id)),
Amount: int64(amount),
ToTelegramId: toUserDb.Telegram.ID,
ToTelegramUser: toUserStrWithoutAt,
@@ -208,10 +216,12 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
// sendHandler invoked when user clicked send on payment confirmation
func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
tx := &SendData{Base: transaction.New(transaction.ID(c.Data))}
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)
log.Errorf("[acceptSendHandler] %s", err.Error())
return
}
sendData := sn.(*SendData)
@@ -219,19 +229,12 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
if sendData.From.Telegram.ID != c.Sender.ID {
return
}
// immediatelly set intransaction to block duplicate calls
err = sendData.Lock(sendData, bot.Bunt)
if err != nil {
log.Errorf("[acceptSendHandler] %s", err)
bot.tryDeleteMessage(c.Message)
return
}
if !sendData.Active {
log.Errorf("[acceptSendHandler] send not active anymore")
// bot.tryDeleteMessage(c.Message)
return
}
defer sendData.Release(sendData, bot.Bunt)
defer sendData.Set(sendData, bot.Bunt)
// // remove buttons from confirmation message
// bot.tryEditMessage(c.Message, MarkdownEscape(sendData.Message), &tb.ReplyMarkup{})
@@ -260,15 +263,15 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
fromUserStr := GetUserStr(from.Telegram)
transactionMemo := fmt.Sprintf("Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
t := NewTransaction(bot, from, to, int(amount), TransactionType("send"))
t := NewTransaction(bot, from, to, amount, TransactionType("send"))
t.Memo = transactionMemo
success, err := t.Send()
if !success || err != nil {
// bot.trySendMessage(c.Sender, sendErrorMessage)
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err)
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err.Error())
log.Errorln(errmsg)
bot.tryEditMessage(c.Message, fmt.Sprintf("%s %s", i18n.Translate(sendData.LanguageCode, "sendErrorMessage"), err), &tb.ReplyMarkup{})
bot.tryEditMessage(c.Message, i18n.Translate(sendData.LanguageCode, "sendErrorMessage"), &tb.ReplyMarkup{})
return
}
sendData.Inactivate(sendData, bot.Bunt)
@@ -299,12 +302,15 @@ func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) {
// reset state immediately
user := LoadUser(ctx)
ResetUserState(user, bot)
tx := &SendData{Base: transaction.New(transaction.ID(c.Data))}
tx := &SendData{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[acceptSendHandler] %s", err)
log.Errorf("[acceptSendHandler] %s", err.Error())
return
}
sendData := sn.(*SendData)
// onnly the correct user can press
if sendData.From.Telegram.ID != c.Sender.ID {
@@ -312,6 +318,5 @@ func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) {
}
// remove buttons from confirmation message
bot.tryEditMessage(c.Message, i18n.Translate(sendData.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
sendData.InTransaction = false
sendData.Inactivate(sendData, bot.Bunt)
}
File diff suppressed because it is too large Load Diff
+296
View File
@@ -0,0 +1,296 @@
package telegram
import (
"context"
"fmt"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/eko/gocache/store"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
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)
user := LoadUser(ctx)
buttons := []tb.Row{}
if len(shops.Shops) > 0 {
buttons = append(buttons, shopKeyboard.Row(browseShopButton))
}
if user.Telegram.ID == shops.Owner.Telegram.ID {
buttons = append(buttons, shopKeyboard.Row(shopNewShopButton, shopSettingsButton))
}
shopKeyboard.Inline(
buttons...,
)
return shopKeyboard
}
func (bot TipBot) shopsSettingsMenu(ctx 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)
shopDeleteShopButton := shopKeyboard.Data("🚫 Delete shops", "shops_deleteshop", shops.ID)
shopDescriptionShopButton := shopKeyboard.Data("💬 Description", "shops_description", shops.ID)
// // shopResetShopButton := shopKeyboard.Data("⚠️ Delete all shops", "shops_reset", shops.ID)
// buttons := []tb.Row{
// shopKeyboard.Row(shopLinkShopButton),
// shopKeyboard.Row(shopDescriptionShopButton),
// shopKeyboard.Row(shopRenameShopButton),
// shopKeyboard.Row(shopDeleteShopButton),
// // shopKeyboard.Row(shopResetShopButton),
// shopKeyboard.Row(shopShopsButton),
// }
// shopKeyboard.Inline(
// buttons...,
// )
button := []tb.Btn{
shopLinkShopButton,
shopDescriptionShopButton,
shopRenameShopButton,
shopDeleteShopButton,
shopShopsButton,
}
shopKeyboard.Inline(buttonWrapper(button, shopKeyboard, 2)...)
return shopKeyboard
}
// shopItemSettingsMenu builds the buttons of the item settings
func (bot TipBot) shopItemSettingsMenu(ctx 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 file", "shop_itemaddfile", item.ID)
shopItemSettingsBackButton = shopKeyboard.Data("⬅️ Back", "shop_itemsettingsback", item.ID)
user := LoadUser(ctx)
buttons := []tb.Row{}
if user.Telegram.ID == shop.Owner.Telegram.ID {
buttons = append(buttons, shopKeyboard.Row(shopItemDeleteButton, shopItemSettingsBackButton))
buttons = append(buttons, shopKeyboard.Row(shopItemTitleButton, shopItemPriceButton))
buttons = append(buttons, shopKeyboard.Row(shopItemAddFileButton))
}
shopKeyboard.Inline(
buttons...,
)
return shopKeyboard
}
// shopItemConfirmBuyMenu builds the buttons to confirm a purchase
func (bot TipBot) shopItemConfirmBuyMenu(ctx 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{}
buttons = append(buttons, shopKeyboard.Row(shopItemBuyButton))
buttons = append(buttons, shopKeyboard.Row(shopItemCancelBuyButton))
shopKeyboard.Inline(
buttons...,
)
return shopKeyboard
}
// shopMenu builds the buttons in the item browser
func (bot TipBot) shopMenu(ctx context.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
user := LoadUser(ctx)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
return nil
}
shopShopsButton := shopKeyboard.Data("⬅️ Back", "shops_shops", shop.ShopsID)
shopAddItemButton = shopKeyboard.Data("✅ New item", "shop_additem", shop.ID)
shopItemSettingsButton = shopKeyboard.Data("⚙️ Settings", "shop_itemsettings", item.ID)
shopNextitemButton = shopKeyboard.Data(">", "shop_nextitem", shop.ID)
shopPrevitemButton = shopKeyboard.Data("<", "shop_previtem", shop.ID)
buyButtonText := "📩 Get"
if item.Price > 0 {
buyButtonText = fmt.Sprintf("Buy (%d sat)", item.Price)
}
shopBuyitemButton = shopKeyboard.Data(buyButtonText, "shop_buyitem", item.ID)
buttons := []tb.Row{}
if user.Telegram.ID == shop.Owner.Telegram.ID {
if len(shop.Items) == 0 {
buttons = append(buttons, shopKeyboard.Row(shopAddItemButton))
} else {
buttons = append(buttons, shopKeyboard.Row(shopAddItemButton, shopItemSettingsButton))
}
}
// publicButtons := []tb.Row{}
if len(shop.Items) > 0 {
if shopView.Page == len(shop.Items)-1 {
// last page
shopNextitemButton = shopKeyboard.Data("x", "shop_nextitem", shop.ID)
}
buttons = append(buttons, shopKeyboard.Row(shopPrevitemButton, shopBuyitemButton, shopNextitemButton))
}
buttons = append(buttons, shopKeyboard.Row(shopShopsButton))
shopKeyboard.Inline(
buttons...,
)
return shopKeyboard
}
// makseShopSelectionButtons produces a list of all buttons with a uniqueString ID
func (bot *TipBot) makseShopSelectionButtons(shops []*Shop, uniqueString string) []tb.Btn {
var buttons []tb.Btn
for _, shop := range shops {
buttons = append(buttons, shopKeyboard.Data(shop.Title, uniqueString, shop.ID))
}
return buttons
}
// -------------- ShopView --------------
// getUserShopview returns ShopView object from cache that holds information about the user's current browsing view
func (bot *TipBot) getUserShopview(ctx 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
}
shopView = sv.(ShopView)
return
}
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))
shopView, err = bot.getUserShopview(ctx, user)
if err != nil {
return
}
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(start int, messages []*tb.Message, bot *TipBot) {
// delete all status messages from telegram
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 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)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
return nil
}
statusMsg := bot.trySendMessage(to, what, options...)
shopView.StatusMessages = append(shopView.StatusMessages, statusMsg)
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
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 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...)
// kick off ticker to remove all messages
ticker := runtime.GetTicker(id, runtime.WithDuration(5*time.Second))
if !ticker.Started {
ticker.Do(func() {
bot.shopViewDeleteAllStatusMsgs(ctx, user, 1)
// removing ticker asap done
runtime.RemoveTicker(id)
})
} else {
ticker.ResetChan <- struct{}{}
}
return statusMsg
}
// --------------- Shop ---------------
// initUserShops is a helper function for creating a Shops for the user in the database
func (bot *TipBot) initUserShops(ctx 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,
}
runtime.IgnoreError(shops.Set(shops, bot.ShopBunt))
return shops, nil
}
// getUserShops returns the Shops for the user
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)
return &Shops{}, err
}
shops := sn.(*Shops)
return shops, nil
}
// addUserShop adds a new Shop to the Shops of a user
func (bot *TipBot) addUserShop(ctx context.Context, user *lnbits.User) (*Shop, error) {
shops, err := bot.getUserShops(ctx, user)
if err != nil {
return &Shop{}, err
}
shopId := fmt.Sprintf("shop-%s", RandStringRunes(10))
shop := &Shop{
Base: storage.New(storage.ID(shopId)),
ID: shopId,
Title: fmt.Sprintf("Shop %d (%s)", len(shops.Shops)+1, shopId),
Owner: user,
Type: "photo",
Items: make(map[string]ShopItem),
LanguageCode: ctx.Value("publicLanguageCode").(string),
ShopsID: shops.ID,
MaxItems: MAX_ITEMS_PER_SHOP,
}
runtime.IgnoreError(shop.Set(shop, bot.ShopBunt))
shops.Shops = append(shops.Shops, shopId)
runtime.IgnoreError(shops.Set(shops, bot.ShopBunt))
return shop, nil
}
// getShop returns the Shop 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 {
log.Errorf("[getShop] %s", err.Error())
return &Shop{}, err
}
shop := sn.(*Shop)
if shop.Owner == nil {
return &Shop{}, fmt.Errorf("shop has no owner")
}
return shop, nil
}
+3 -3
View File
@@ -85,7 +85,7 @@ func (bot TipBot) createWallet(user *lnbits.User) error {
internal.Configuration.Lnbits.AdminId,
UserStr)
if err != nil {
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err)
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err.Error())
log.Errorln(errormsg)
return err
}
@@ -94,7 +94,7 @@ func (bot TipBot) createWallet(user *lnbits.User) error {
user.Name = u.Name
wallet, err := bot.Client.Wallets(*user)
if err != nil {
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err)
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err.Error())
log.Errorln(errormsg)
return err
}
@@ -104,7 +104,7 @@ func (bot TipBot) createWallet(user *lnbits.User) error {
user.CreatedAt = time.Now()
err = UpdateUserRecord(user, bot)
if err != nil {
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err)
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err.Error())
log.Errorln(errormsg)
return err
}
+25
View File
@@ -0,0 +1,25 @@
package telegram
import (
"context"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type StateCallbackMessage map[lnbits.UserStateKey]func(ctx context.Context, m *tb.Message)
var stateCallbackMessage StateCallbackMessage
func initializeStateCallbackMessage(bot *TipBot) {
stateCallbackMessage = StateCallbackMessage{
lnbits.UserStateLNURLEnterAmount: bot.enterAmountHandler,
lnbits.UserEnterAmount: bot.enterAmountHandler,
lnbits.UserEnterUser: bot.enterUserHandler,
lnbits.UserEnterShopTitle: bot.enterShopTitleHandler,
lnbits.UserStateShopItemSendPhoto: bot.addShopItemPhoto,
lnbits.UserStateShopItemSendPrice: bot.enterShopItemPriceHandler,
lnbits.UserStateShopItemSendTitle: bot.enterShopItemTitleHandler,
lnbits.UserStateShopItemSendItemFile: bot.addItemFileHandler,
lnbits.UserEnterShopsDescription: bot.enterShopsDescriptionHandler,
}
}
+53 -18
View File
@@ -2,16 +2,57 @@ package telegram
import (
"fmt"
"strconv"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/rate"
"github.com/eko/gocache/store"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
"time"
)
// 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 getChatIdFromRecipient(to tb.Recipient) (int64, error) {
chatId, err := strconv.ParseInt(to.Recipient(), 10, 64)
if err != nil {
return 0, err
}
return chatId, nil
}
func (bot TipBot) tryForwardMessage(to tb.Recipient, what tb.Editable, options ...interface{}) (msg *tb.Message) {
rate.CheckLimit(to)
msg, err := bot.Telegram.Forward(to, what, options...)
// ChatId is used for the keyboard
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, appendMainMenu(chatId, options)...)
if err != nil {
log.Warnln(err.Error())
}
@@ -19,7 +60,13 @@ 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)
msg, err := bot.Telegram.Send(to, what, options...)
// ChatId is used for the keyboard
chatId, err := getChatIdFromRecipient(to)
if err != nil {
log.Errorf("[trySendMessage] error converting message recipient to int64: %v", err)
return
}
msg, err = bot.Telegram.Send(to, what, appendMainMenu(chatId, options)...)
if err != nil {
log.Warnln(err.Error())
}
@@ -28,7 +75,7 @@ func (bot TipBot) trySendMessage(to tb.Recipient, what interface{}, options ...i
func (bot TipBot) tryReplyMessage(to *tb.Message, what interface{}, options ...interface{}) (msg *tb.Message) {
rate.CheckLimit(to)
msg, err := bot.Telegram.Reply(to, what, options...)
msg, err := bot.Telegram.Reply(to, what, appendMainMenu(to.Chat.ID, options)...)
if err != nil {
log.Warnln(err.Error())
}
@@ -36,12 +83,10 @@ func (bot TipBot) tryReplyMessage(to *tb.Message, what interface{}, options ...i
}
func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...interface{}) (msg *tb.Message) {
if !allowedToPerformAction(bot, to, isAdminAndCanEdit) {
return
}
rate.CheckLimit(to)
var err error
msg, err = bot.Telegram.Edit(to, what, options...)
_, chatId := to.MessageSig()
msg, err = bot.Telegram.Edit(to, what, appendMainMenu(chatId, options)...)
if err != nil {
log.Warnln(err.Error())
}
@@ -101,13 +146,3 @@ func isAdminAndCanDelete(members []tb.ChatMember, me *tb.User) bool {
}
return false
}
// isAdminAndCanEdit will check if me is in members list and allowed to edit messages
func isAdminAndCanEdit(members []tb.ChatMember, me *tb.User) bool {
for _, admin := range members {
if admin.User.ID == me.ID {
return admin.CanEditMessages
}
}
return false
}
+4 -13
View File
@@ -12,7 +12,7 @@ import (
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func (bot TipBot) anyTextHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) anyTextHandler(ctx context.Context, m *tb.Message) {
if m.Chat.Type != tb.ChatPrivate {
return
}
@@ -36,18 +36,10 @@ func (bot TipBot) anyTextHandler(ctx context.Context, m *tb.Message) {
bot.lnurlHandler(ctx, m)
return
}
// could be a LNURL
// var lnurlregex = regexp.MustCompile(`.*?((lnurl)([0-9]{1,}[a-z0-9]+){1})`)
// inputs asked for
if user.StateKey == lnbits.UserStateLNURLEnterAmount || user.StateKey == lnbits.UserEnterAmount {
bot.enterAmountHandler(ctx, m)
if c := stateCallbackMessage[user.StateKey]; c != nil {
c(ctx, m)
//ResetUserState(user, bot)
}
if user.StateKey == lnbits.UserEnterUser {
bot.enterUserHandler(ctx, m)
}
}
type EnterUserStateData struct {
@@ -114,7 +106,6 @@ func (bot *TipBot) enterUserHandler(ctx context.Context, m *tb.Message) {
switch EnterUserStateData.Type {
case "CreateSendState":
m.Text = fmt.Sprintf("/send %s", userstr)
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
bot.sendHandler(ctx, m)
return
default:
+2 -3
View File
@@ -69,7 +69,6 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
}
// TIP COMMAND IS VALID
from := LoadUser(ctx)
to := LoadReplyToUser(ctx)
if from.Telegram.ID == to.Telegram.ID {
@@ -110,8 +109,8 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
success, err := t.Send()
if !success {
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, Translate(ctx, "tipErrorMessage"))
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err)
bot.trySendMessage(m.Sender, fmt.Sprintf("%s %s", Translate(ctx, "tipErrorMessage"), err))
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err.Error())
log.Warnln(errMsg)
return
}
+39 -44
View File
@@ -26,17 +26,22 @@ const (
type TipTooltip struct {
Message
TipAmount int `json:"tip_amount"`
ID string `json:"id"`
TipAmount int64 `json:"tip_amount"`
Ntips int `json:"ntips"`
LastTip time.Time `json:"last_tip"`
Tippers []*tb.User `json:"tippers"`
}
func (ttt TipTooltip) Key() string {
return fmt.Sprintf("tip-tool-tip:%s", ttt.ID)
}
const maxNamesInTipperMessage = 5
type TipTooltipOption func(m *TipTooltip)
func TipAmount(amount int) TipTooltipOption {
func TipAmount(amount int64) TipTooltipOption {
return func(m *TipTooltip) {
m.TipAmount = amount
}
@@ -50,6 +55,7 @@ func Tips(nTips int) TipTooltipOption {
func NewTipTooltip(m *tb.Message, opts ...TipTooltipOption) *TipTooltip {
tipTooltip := &TipTooltip{
ID: fmt.Sprintf("%d-%d", m.Chat.ID, m.ReplyTo.ID),
Message: Message{
Message: m,
},
@@ -99,8 +105,8 @@ func getTippersString(tippers []*tb.User) string {
}
// tipTooltipExists checks if this tip is already known
func tipTooltipExists(replyToId int, bot *TipBot) (bool, *TipTooltip) {
message := NewTipTooltip(&tb.Message{ReplyTo: &tb.Message{ID: replyToId}})
func tipTooltipExists(m *tb.Message, bot *TipBot) (bool, *TipTooltip) {
message := NewTipTooltip(&tb.Message{Chat: &tb.Chat{ID: m.Chat.ID}, ReplyTo: &tb.Message{ID: m.ReplyTo.ID}})
err := bot.Bunt.Get(message)
if err != nil {
return false, message
@@ -110,49 +116,48 @@ func tipTooltipExists(replyToId int, bot *TipBot) (bool, *TipTooltip) {
}
// tipTooltipHandler function to update the tooltip below a tipped message. either updates or creates initial tip tool tip
func tipTooltipHandler(m *tb.Message, bot *TipBot, amount int, initializedWallet bool) (hasTip bool) {
func tipTooltipHandler(m *tb.Message, bot *TipBot, amount int64, initializedWallet bool) (hasTip bool) {
// todo: this crashes if the tooltip message (maybe also the original tipped message) was deleted in the mean time!!! need to check for existence!
hasTip, ttt := tipTooltipExists(m.ReplyTo.ID, bot)
hasTip, ttt := tipTooltipExists(m, bot)
log.Debugf("[tip] %s has tip: %t", ttt.ID, hasTip)
if hasTip {
// update the tooltip with new tippers
err := ttt.updateTooltip(bot, m.Sender, amount, !initializedWallet)
if err != nil {
log.Println(err)
log.Errorln(err)
// could not update the message (return false to )
return false
}
} else {
tipmsg := fmt.Sprintf(tooltipTipAmountMessage, amount)
userStr := GetUserStrMd(m.Sender)
tipmsg = fmt.Sprintf(tooltipSingleTipMessage, tipmsg, userStr)
if !initializedWallet {
tipmsg = tipmsg + fmt.Sprintf("\n%s", fmt.Sprintf(tooltipChatWithBotMessage, GetUserStrMd(bot.Telegram.Me)))
}
msg, err := bot.Telegram.Reply(m.ReplyTo, tipmsg, tb.Silent)
if err != nil {
log.Errorf("[tipTooltipHandler Reply] %s", err.Error())
// todo: in case of error we should do something better than just return 0
return false
}
message := NewTipTooltip(msg, TipAmount(amount), Tips(1))
message.Tippers = appendUinqueUsersToSlice(message.Tippers, m.Sender)
runtime.IgnoreError(bot.Bunt.Set(message))
newToolTip(m, bot, amount, initializedWallet)
}
// first call will return false, every following call will return true
return hasTip
}
func newToolTip(m *tb.Message, bot *TipBot, amount int64, initializedWallet bool) {
tipmsg := fmt.Sprintf(tooltipTipAmountMessage, amount)
userStr := GetUserStrMd(m.Sender)
tipmsg = fmt.Sprintf(tooltipSingleTipMessage, tipmsg, userStr)
if !initializedWallet {
tipmsg = tipmsg + fmt.Sprintf("\n%s", fmt.Sprintf(tooltipChatWithBotMessage, GetUserStrMd(bot.Telegram.Me)))
}
msg := bot.tryReplyMessage(m.ReplyTo, tipmsg, tb.Silent)
message := NewTipTooltip(msg, TipAmount(amount), Tips(1))
message.Tippers = appendUinqueUsersToSlice(message.Tippers, m.Sender)
runtime.IgnoreError(bot.Bunt.Set(message))
log.Debugf("[newToolTip]: New reply message: %d (Bunt: %s)", msg.ID, message.Key())
}
// updateToolTip updates existing tip tool tip in Telegram
func (ttt *TipTooltip) updateTooltip(bot *TipBot, user *tb.User, amount int, notInitializedWallet bool) error {
func (ttt *TipTooltip) updateTooltip(bot *TipBot, user *tb.User, amount int64, notInitializedWallet bool) error {
ttt.TipAmount += amount
ttt.Ntips += 1
ttt.Tippers = appendUinqueUsersToSlice(ttt.Tippers, user)
ttt.LastTip = time.Now()
err := ttt.editTooltip(bot, notInitializedWallet)
if err != nil {
return err
}
ttt.editTooltip(bot, notInitializedWallet)
log.Debugf("[updateTooltip]: Update tip tooltip (Bunt: %s)", ttt.Key())
return bot.Bunt.Set(ttt)
}
@@ -162,16 +167,14 @@ func tipTooltipInitializedHandler(user *tb.User, bot TipBot) {
err := tx.Ascend(MessageOrderedByReplyToFrom, func(key, value string) bool {
replyToUserId := gjson.Get(value, MessageOrderedByReplyToFrom)
if replyToUserId.String() == strconv.FormatInt(user.ID, 10) {
log.Debugln("loading persistent tip tool tip messages")
log.Debugln("[tipTooltipInitializedHandler] loading persistent tip tool tip messages")
ttt := &TipTooltip{}
err := json.Unmarshal([]byte(value), ttt)
if err != nil {
log.Errorln(err)
}
err = ttt.editTooltip(&bot, false)
if err != nil {
log.Errorf("[tipTooltipInitializedHandler] could not edit tooltip: %s", err.Error())
}
// edit to remove the "chat with bot" message
ttt.editTooltip(&bot, false)
}
return true
@@ -180,17 +183,9 @@ func tipTooltipInitializedHandler(user *tb.User, bot TipBot) {
}))
}
func (ttt TipTooltip) Key() string {
return fmt.Sprintf("tip-tool-tip:%s", strconv.Itoa(ttt.Message.Message.ReplyTo.ID))
}
// editTooltip updates the tooltip message with the new tip amount and tippers and edits it
func (ttt *TipTooltip) editTooltip(bot *TipBot, notInitializedWallet bool) error {
func (ttt *TipTooltip) editTooltip(bot *TipBot, notInitializedWallet bool) {
tipToolTip := ttt.getUpdatedTipTooltipMessage(GetUserStrMd(bot.Telegram.Me), notInitializedWallet)
m, err := bot.Telegram.Edit(ttt.Message.Message, tipToolTip)
if err != nil {
return err
}
ttt.Message.Message.Text = m.Text
return nil
bot.tryEditMessage(ttt.Message.Message, tipToolTip)
// ttt.Message.Message.Text = m.Text
}
+1 -1
View File
@@ -45,7 +45,7 @@ func Test_getTippersString(t *testing.T) {
func TestMessage_getTooltipMessage(t *testing.T) {
type fields struct {
Message Message
TipAmount int
TipAmount int64
Ntips int
LastTip time.Time
Tippers []*tb.User
+20 -29
View File
@@ -21,7 +21,7 @@ type Transaction struct {
FromUser string `json:"from_user"`
ToUser string `json:"to_user"`
Type string `json:"type"`
Amount int `json:"amount"`
Amount int64 `json:"amount"`
ChatID int64 `json:"chat_id"`
ChatName string `json:"chat_name"`
Memo string `json:"memo"`
@@ -48,7 +48,7 @@ func TransactionType(transactionType string) TransactionOption {
}
}
func NewTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int, opts ...TransactionOption) *Transaction {
func NewTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int64, opts ...TransactionOption) *Transaction {
t := &Transaction{
Bot: bot,
From: from,
@@ -70,18 +70,9 @@ func NewTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int,
}
func (t *Transaction) Send() (success bool, err error) {
// maybe remove comments, GTP-3 dreamed this up but it's nice:
// if t.From.ID == t.To.ID {
// err = fmt.Errorf("Can not send transaction to yourself.")
// return false, err
// }
// todo: remove this commend if the backend is back up
success, err = t.SendTransaction(t.Bot, t.From, t.To, t.Amount, t.Memo)
// success = true
if success {
t.Success = success
// TODO: call post-send methods
}
// save transaction to db
@@ -90,29 +81,29 @@ func (t *Transaction) Send() (success bool, err error) {
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err.Error())
log.Errorln(errMsg)
}
return success, err
}
func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int, memo string) (bool, error) {
func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int64, memo string) (bool, error) {
fromUserStr := GetUserStr(from.Telegram)
toUserStr := GetUserStr(to.Telegram)
t.FromWallet = from.Wallet.ID
t.FromLNbitsID = from.ID
// check if fromUser has balance
balance, err := bot.GetUserBalance(from)
if err != nil {
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
@@ -125,7 +116,7 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
Memo: memo},
bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[SendTransaction] Error: Could not create invoice for user %s", toUserStr)
errmsg := fmt.Sprintf("[Send] Error: Could not create invoice for user %s", toUserStr)
log.Errorln(errmsg)
return false, err
}
@@ -133,8 +124,8 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
// pay invoice
_, err = from.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[SendTransaction] Error: Payment from %s to %s of %d sat failed", fromUserStr, toUserStr, amount)
log.Errorln(errmsg)
errmsg := fmt.Sprintf("[Send] Payment failed (%s to %s of %d sat): %s", fromUserStr, toUserStr, amount, err.Error())
log.Warnf(errmsg)
return false, err
}
return true, err
+4 -4
View File
@@ -60,16 +60,16 @@ func appendUinqueUsersToSlice(slice []*tb.User, i *tb.User) []*tb.User {
return append(slice, i)
}
func (bot *TipBot) GetUserBalanceCached(user *lnbits.User) (amount int, err error) {
func (bot *TipBot) GetUserBalanceCached(user *lnbits.User) (amount int64, err error) {
u, err := bot.Cache.Get(fmt.Sprintf("%s_balance", user.Name))
if err != nil {
return bot.GetUserBalance(user)
}
cachedBalance := u.(int)
cachedBalance := u.(int64)
return cachedBalance, nil
}
func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int, err error) {
func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
wallet, err := bot.Client.Info(*user.Wallet)
if err != nil {
errmsg := fmt.Sprintf("[GetUserBalance] Error: Couldn't fetch user %s's info from LNbits: %s", GetUserStr(user.Telegram), err.Error())
@@ -82,7 +82,7 @@ func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int, err error) {
return
}
// msat to sat
amount = int(wallet.Balance) / 1000
amount = int64(wallet.Balance) / 1000
log.Infof("[GetUserBalance] %s's balance: %d sat\n", GetUserStr(user.Telegram), amount)
// update user balance in cache
+4 -1
View File
@@ -1,6 +1,7 @@
package main
import (
"net/http"
"runtime/debug"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits/webhook"
@@ -8,11 +9,12 @@ import (
"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.InfoLevel)
log.SetLevel(log.TraceLevel)
customFormatter := new(log.TextFormatter)
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
customFormatter.FullTimestamp = true
@@ -22,6 +24,7 @@ func setLogger() {
func main() {
// set logger
setLogger()
go http.ListenAndServe("0.0.0.0:6060", nil)
defer withRecovery()
bot := telegram.NewBot()
webhook.NewServer(&bot)
+1 -1
View File
@@ -21,7 +21,7 @@ func IsInvoice(message string) bool {
func IsLnurl(message string) bool {
message = strings.ToLower(message)
if strings.HasPrefix(message, "lnurl") {
if strings.HasPrefix(message, "lnurl") || strings.HasPrefix(message, "lightning:lnurl") {
// string must be a single word
if !strings.Contains(message, " ") {
return true