Compare commits

...
121 Commits
Author SHA1 Message Date
lngohumble f978d98252 volcano initial commit 2021-12-27 11:58:19 +01:00
25dc9d7b34 add edit stack lifo (#231)
* add edit stack lifo

* remove log message

* 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>

* 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>

* Log oncemap (#233)

* speed up tx lock

* yolo master

* logging

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* Balance button (#236)

* speed up tx lock

* yolo master

* blanace button

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* Balance on invoice (#237)

* speed up tx lock

* yolo master

* balance check on invoice

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* add mutex http endpoints (#238)

* Faucet balance update (#239)

* speed up tx lock

* yolo master

* balance check faucet

* limit reset

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* Unlock admin (#240)

* add mutex http endpoints

* remove mutex by id

* remove mutex by id

Co-authored-by: lngohumble <lngohumble@gmail.com>

* fix nLocks (#241)

* using shop.base.id (#242)

* using shop.base.id

* using shop.base.id

* using shop.base.id

* Adjust log levels (#244)

* speed up tx lock

* yolo master

* better log

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* fix edit signature rate limiter (#234)

* Skip duplicate edits (#245)

* speed up tx lock

* yolo master

* skip duplicate edit

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>

* only remove on unlock (#246)

* add edit stack lifo

* finish faucet corrected

* improve edit stack

* edit.go

* uncomment faucet check

Co-authored-by: LightningTipBot <88730856+LightningTipBot@users.noreply.github.com>
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 20:57:38 +01:00
gohumbleandGitHub 01423827b7 Fix shop v1 (#243)
* using shop.base.id

* using shop.base.id

* using shop.base.id

* remove index from delete status messages

* fix delete status messages
2021-12-26 20:46:56 +01:00
gohumbleandGitHub f1df1e6377 only remove on unlock (#246) 2021-12-26 16:58:05 +01:00
1e5f7b1169 Skip duplicate edits (#245)
* speed up tx lock

* yolo master

* skip duplicate edit

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 16:46:04 +01:00
gohumbleandGitHub 9c6062f317 fix edit signature rate limiter (#234) 2021-12-26 16:37:43 +01:00
fc7247c72a Adjust log levels (#244)
* speed up tx lock

* yolo master

* better log

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 16:30:27 +01:00
gohumbleandGitHub c23d69e8f1 using shop.base.id (#242)
* using shop.base.id

* using shop.base.id

* using shop.base.id
2021-12-26 15:38:26 +01:00
gohumbleandGitHub 35d5ed8d8e fix nLocks (#241) 2021-12-26 15:12:18 +01:00
07ccc6cc28 Unlock admin (#240)
* add mutex http endpoints

* remove mutex by id

* remove mutex by id

Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-12-26 14:51:10 +01:00
2ef798e56a Faucet balance update (#239)
* speed up tx lock

* yolo master

* balance check faucet

* limit reset

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 14:46:09 +01:00
gohumbleandGitHub 24e4212a93 add mutex http endpoints (#238) 2021-12-26 14:20:50 +01:00
6851badfab Balance on invoice (#237)
* speed up tx lock

* yolo master

* balance check on invoice

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 03:30:41 +01:00
cbedc5c147 Balance button (#236)
* speed up tx lock

* yolo master

* blanace button

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 03:05:25 +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
38251600f9 tx timeout sleep faster (#153)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-06 22:37:22 +01:00
aaa8a3cc19 WIP: rate limiter per chat (#86)
* add rate limiter per chat

* differentiate between global and chat rate limiting

* remove diffs

* resolve conflicts

* resolve conflict

* refactor limiter

* rename

* rename

* logs

* remove logs

* reset buckets

* new rate limiter

* fix comments

* separate id and global limiter

* rename stuff

* reset bucket size

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-06 22:22:02 +01:00
gohumbleandGitHub 25d9b8af3b Check admin rights (#152)
* add rightsToDoAction

* comments

* comments

* typo

* check for id

* return CanEditMessages
2021-12-06 20:08:33 +01:00
ba6bf0a317 telebot fork user ID int64 (#151)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-01 11:24:28 +01:00
LightningTipBotandGitHub 0abe56dfba Revert "telebot fork user ID int64 (#149)" (#150)
This reverts commit 7c8ba7895d.
2021-12-01 08:59:51 +01:00
7c8ba7895d telebot fork user ID int64 (#149)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-01 08:52:47 +01:00
eeb9d5224e revert (#148)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-01 07:11:49 +01:00
79112717cf Telebot update (#146)
* update telebot

* test message

* revert

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-01 07:08:46 +01:00
4a9a77d5f1 Telebot update (#145)
* update telebot

* test message

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-01 06:05:20 +01:00
4ba892908b update telebot (#144)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-01 05:32:53 +01:00
3891c70344 banned prefix filter (#141)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-26 13:36:02 +01:00
6e6c9e02a4 donate message (#140)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-19 21:23:39 +01:00
488fab7f9f expressive errors (#139)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-18 22:04:29 +01:00
8f569ed4c3 send input (#138)
* send input

* remove message limiter

* write invoice into tx db

* do not delete tip twice

* hide link after 60 sedondw

* refactor button text update

* remove print

* translations enter user

* add tr

* no error on invalid user input

* printing fix

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-17 19:51:51 +01:00
3f26f0b44f copy handlelnurl (#137)
* copy handlelnurl

* rephrase error

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-16 20:40:19 +01:00
1f25cc6ded Add russian translation (#136)
* Add Russian translation

* turn on ru.toml

* load gently

Co-authored-by: Filiph Protsenko <filprocenko@gmail.com>
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-15 16:41:34 +01:00
69b0dd5a4a Lnurl errors localized1 (#134)
* verbose errors

* add translations

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-15 11:42:35 +01:00
calleandGitHub e1d858752f emojis for logging (#133)
* emojis for logging

* emojis for logging
2021-11-15 10:18:57 +01:00
88bbd4d2cf Fix lnurlpserver (#132)
* fix server

* go-lnurl v1.8.4

* encode

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-15 01:12:52 +01:00
8c4adb4dd4 Fix lnurlpserver (#131)
* fix server

* go-lnurl v1.8.4

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-15 01:03:09 +01:00
9290f55fa4 fix server (#130)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-11-15 00:02:10 +01:00
0653498e0f Lnurl withdraw (#129)
* go-lnurl --> v1.8.4

* clean up comments

* delete HandleLNURL()

* lnurl-withdrawal

* actual file

* remove comments

* remove comments

* refactor translation

* translations

* add type check and

* translations

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-11-14 22:25:47 +01:00
gohumbleandGitHub dd57247266 increase lnbits pay timeout (#127) 2021-11-14 22:03:14 +01:00
gohumbleandGitHub 051174bd1c using anyChosenInlineHandler (#128)
* using anyChosenInlineHandler

* error logging
2021-11-14 21:57:54 +01:00
KotyandGitHub 5eaf380e91 Tipjar translations into Spanish and Portuguese (#122)
* For mango-selling grannies in Brazil

* Update pt-br.toml

#TIPJAR pt-br translation

* Update es.toml :)

#TIPJAR es ahora alcancía

* Update es.toml

minor fix

* Update pt-br.toml

Minor fixes to pt-br.toml file

* remove pt.toml
2021-11-14 21:53:48 +01:00
LightningTipBotandGitHub fb73c1fe08 markdown escape usernames (#126) 2021-11-11 11:56:53 +01:00
LightningTipBotandGitHub 4a03724540 fix lnurl parsing and comment saving (#125) 2021-11-09 17:54:35 +01:00
LightningTipBotandGitHub 5725a0c9c0 do not return (#123)
* do not return

* warn not error
2021-11-03 20:08:56 +01:00
LightningTipBotandGitHub d8a98ad433 fix (#120) 2021-11-01 19:03:24 +01:00
68 changed files with 5306 additions and 937 deletions
+7 -2
View File
@@ -5,20 +5,25 @@ go 1.15
require (
github.com/BurntSushi/toml v0.3.1
github.com/eko/gocache v1.2.0
github.com/fiatjaf/go-lnurl v1.4.0
github.com/fiatjaf/go-lnurl v1.8.4
github.com/fiatjaf/ln-decodepay v1.1.0
github.com/gorilla/mux v1.8.0
github.com/imroc/req v0.3.0
github.com/jinzhu/configor v1.2.1
github.com/makiuchi-d/gozxing v0.0.2
github.com/nicksnyder/go-i18n/v2 v2.1.2
github.com/orcaman/concurrent-map v1.0.0
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/sethvargo/go-limiter v0.7.2
github.com/sirupsen/logrus v1.6.0
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
github.com/tidwall/buntdb v1.2.7
github.com/tidwall/gjson v1.10.2
golang.org/x/text v0.3.5
gopkg.in/tucnak/telebot.v2 v2.3.5
golang.org/x/time v0.0.0-20191024005414-555d28b269f0
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211217193303-c005cce171ac
gorm.io/driver/sqlite v1.1.4
gorm.io/gorm v1.21.12
)
// replace gopkg.in/lightningtipbot/telebot.v2 => ../telebot
+24 -2
View File
@@ -137,6 +137,10 @@ github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLi
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fiatjaf/go-lnurl v1.4.0 h1:hVFEEJD2A9D6ojEcqLyD54CM2ZJ9Tzs2jNKw/GNq52A=
github.com/fiatjaf/go-lnurl v1.4.0/go.mod h1:BqA8WXAOzntF7Z3EkVO7DfP4y5rhWUmJ/Bu9KBke+rs=
github.com/fiatjaf/go-lnurl v1.8.3 h1:ONQUQsXIZKkzrzax2SMUr5W0PreluhO4tct1JM0V/MA=
github.com/fiatjaf/go-lnurl v1.8.3/go.mod h1:0PPdV2GFnJK97ztksEIwrcEUVTothAKJsmzqPphAQhs=
github.com/fiatjaf/go-lnurl v1.8.4 h1:uVH8833lVgvNqW3S0qr0I8VsIId5mVw0lE0KnEjgh/o=
github.com/fiatjaf/go-lnurl v1.8.4/go.mod h1:0PPdV2GFnJK97ztksEIwrcEUVTothAKJsmzqPphAQhs=
github.com/fiatjaf/ln-decodepay v1.1.0 h1:HigjqNH+ApiO6gm7RV23jXNFuvwq+zgsWl4BJAfPWwE=
github.com/fiatjaf/ln-decodepay v1.1.0/go.mod h1:2qdTT95b8Z4dfuxiZxXuJ1M7bQ9CrLieEA1DKC50q6s=
github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw=
@@ -393,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=
@@ -449,6 +455,8 @@ github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQD
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E=
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
github.com/sethvargo/go-limiter v0.7.2 h1:FgC4N7RMpV5gMrUdda15FaFTkQ/L4fEqM7seXMs4oO8=
github.com/sethvargo/go-limiter v0.7.2/go.mod h1:C0kbSFbiriE5k2FFOe18M1YZbAR2Fiwf72uGu0CXCcU=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.2.0 h1:juTguoYk5qI21pwyTXY3B3Y5cOTH3ZUyZCg1v/mihuo=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
@@ -645,7 +653,9 @@ golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2 h1:+DCIGbF/swA92ohVg0//6X2IVY3KZs6p9mix0ziNYJM=
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0 h1:/5xXl8Y5W96D+TtHSlonuFqGHIWVuyCkGJLwGh9JJFs=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
@@ -712,6 +722,18 @@ gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o=
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/lightningtipbot/telebot.v2 v2.3.5 h1:TdMJTlG8kvepsvZdy/gPeYEBdwKdwFFjH1AQTua9BOU=
gopkg.in/lightningtipbot/telebot.v2 v2.3.5/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
gopkg.in/lightningtipbot/telebot.v2 v2.4.1 h1:bUOFHtHhuhPekjHGe1Q1BmITvtBLdQI4yjSMC405KcU=
gopkg.in/lightningtipbot/telebot.v2 v2.4.1/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201070229-f317e8453e9f h1:BnYlAEmRJi8YEcSbXO6PlAVwl7WpKJvMqkijHZmO8Gw=
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=
@@ -722,8 +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.3.5 h1:TdMJTlG8kvepsvZdy/gPeYEBdwKdwFFjH1AQTua9BOU=
gopkg.in/tucnak/telebot.v2 v2.3.5/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
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"`
}
+1
View File
@@ -25,6 +25,7 @@ func RegisterLanguages() *i18n.Bundle {
bundle.LoadMessageFile("translations/pt-br.toml")
bundle.LoadMessageFile("translations/tr.toml")
bundle.LoadMessageFile("translations/id.toml")
bundle.LoadMessageFile("translations/ru.toml")
return bundle
}
func Translate(languageCode string, MessgeID string) string {
+4 -1
View File
@@ -2,6 +2,7 @@ package lnbits
import (
"github.com/imroc/req"
"time"
)
// NewClient returns a new lnbits api client. Pass your API key and url here.
@@ -155,7 +156,9 @@ func (w Wallet) Pay(params PaymentParams, c *Client) (wtx BitInvoice, err error)
"Accept": "application/json",
"X-Api-Key": w.Adminkey,
}
resp, err := req.Post(c.url+"/api/v1/payments", adminHeader, req.BodyJSON(&params))
r := req.New()
r.SetTimeout(time.Hour * 24)
resp, err := r.Post(c.url+"/api/v1/payments", adminHeader, req.BodyJSON(&params))
if err != nil {
return
}
+10 -1
View File
@@ -4,7 +4,7 @@ import (
"time"
"github.com/imroc/req"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type Client struct {
@@ -34,6 +34,15 @@ const (
UserStateConfirmLNURLPay
UserEnterAmount
UserHasEnteredAmount
UserEnterUser
UserHasEnteredUser
UserEnterShopTitle
UserStateShopItemSendPhoto
UserStateShopItemSendTitle
UserStateShopItemSendDescription
UserStateShopItemSendPrice
UserStateShopItemSendItemFile
UserEnterShopsDescription
)
type UserStateKey int
+39 -40
View File
@@ -3,29 +3,25 @@ package webhook
import (
"encoding/json"
"fmt"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"time"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"net/http"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/gorilla/mux"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
)
const (
// invoiceReceivedMessage = "⚡️ You received %d sat."
)
type Server struct {
httpServer *http.Server
bot *tb.Bot
@@ -35,17 +31,16 @@ type Server struct {
}
type Webhook struct {
CheckingID string `json:"checking_id"`
Pending int `json:"pending"`
Amount int `json:"amount"`
Fee int `json:"fee"`
Memo string `json:"memo"`
Time int `json:"time"`
Bolt11 string `json:"bolt11"`
Preimage string `json:"preimage"`
PaymentHash string `json:"payment_hash"`
Extra struct {
} `json:"extra"`
CheckingID string `json:"checking_id"`
Pending bool `json:"pending"`
Amount int64 `json:"amount"`
Fee int64 `json:"fee"`
Memo string `json:"memo"`
Time int64 `json:"time"`
Bolt11 string `json:"bolt11"`
Preimage string `json:"preimage"`
PaymentHash string `json:"payment_hash"`
Extra struct{} `json:"extra"`
WalletID string `json:"wallet_id"`
Webhook string `json:"webhook"`
WebhookStatus interface{} `json:"webhook_status"`
@@ -53,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,
}
@@ -86,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.", user.Telegram.Username, user.Telegram.ID, depositEvent.Amount/1000))
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), depositEvent.Amount/1000))
if err != nil {
log.Errorln(err)
}
log.Infoln(fmt.Sprintf("[⚡️ WebHook] User %s (%d) received invoice of %d sat.", telegram.GetUserStr(user.Telegram), user.Telegram.ID, webhookEvent.Amount/1000))
// if this invoice is saved in bunt.db, we load it and display the comment from an LNURL invoice
tx := &lnurl.Invoice{PaymentHash: depositEvent.PaymentHash}
err = w.buntdb.Get(tx)
writer.WriteHeader(200)
// trigger invoice events
txInvoiceEvent := &telegram.InvoiceEvent{Invoice: &telegram.Invoice{PaymentHash: webhookEvent.PaymentHash}}
err = w.buntdb.Get(txInvoiceEvent)
if err != nil {
log.Errorln(err)
} else {
if len(tx.Comment) > 0 {
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(`✉️ %s`, str.MarkdownEscape(tx.Comment)))
if err != nil {
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)
}
}
+51 -51
View File
@@ -3,7 +3,6 @@ package lnurl
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/url"
@@ -12,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) {
@@ -41,17 +39,17 @@ func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
} else {
stringAmount := request.FormValue("amount")
if stringAmount == "" {
NotFoundHandler(writer, fmt.Errorf("[serveLNURLpSecond] Form value 'amount' is not set"))
NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Form value 'amount' is not set"))
return
}
amount, parseError := strconv.Atoi(stringAmount)
if parseError != nil {
NotFoundHandler(writer, fmt.Errorf("[serveLNURLpSecond] Couldn't cast amount to int %v", parseError))
NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int %v", parseError))
return
}
comment := request.FormValue("comment")
if len(comment) > CommentAllowed {
NotFoundHandler(writer, fmt.Errorf("[serveLNURLpSecond] Comment is too long"))
NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Comment is too long"))
return
}
response, err = w.serveLNURLpSecond(username, int64(amount), comment)
@@ -59,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)
@@ -78,37 +76,32 @@ func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
// serveLNURLpFirst serves the first part of the LNURLp protocol with the endpoint
// to call and the metadata that matches the description hash of the second response
func (w Server) serveLNURLpFirst(username string) (*lnurl.LNURLPayResponse1, error) {
func (w Server) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error) {
log.Infof("[LNURL] Serving endpoint for user %s", username)
callbackURL, err := url.Parse(fmt.Sprintf("%s/%s/%s", w.callbackHostname.String(), lnurlEndpoint, username))
if err != nil {
return nil, err
}
metadata := w.metaData(username)
jsonMeta, err := json.Marshal(metadata)
if err != nil {
return nil, err
}
return &lnurl.LNURLPayResponse1{
return &lnurl.LNURLPayParams{
LNURLResponse: lnurl.LNURLResponse{Status: statusOk},
Tag: payRequestTag,
Callback: callbackURL.String(),
CallbackURL: callbackURL, // probably no need to set this here
MinSendable: minSendable,
MaxSendable: MaxSendable,
EncodedMetadata: string(jsonMeta),
EncodedMetadata: metadata.Encode(),
CommentAllowed: CommentAllowed,
}, nil
}
// serveLNURLpSecond serves the second LNURL response with the payment request with the correct description hash
func (w Server) serveLNURLpSecond(username string, amount int64, comment string) (*lnurl.LNURLPayResponse2, error) {
func (w 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.LNURLPayResponse2{
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: statusError,
Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", minSendable, MaxSendable)},
@@ -116,7 +109,7 @@ func (w Server) serveLNURLpSecond(username string, amount int64, comment string)
}
// check comment length
if len(comment) > CommentAllowed {
return &lnurl.LNURLPayResponse2{
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: statusError,
Reason: fmt.Sprintf("Comment too long (max: %d characters).", CommentAllowed)},
@@ -136,14 +129,14 @@ func (w Server) serveLNURLpSecond(username string, amount int64, comment string)
}
if tx.Error != nil {
return &lnurl.LNURLPayResponse2{
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: statusError,
Reason: fmt.Sprintf("Invalid user.")},
}, fmt.Errorf("[GetUser] Couldn't fetch user info from database: %v", tx.Error)
}
if user.Wallet == nil {
return &lnurl.LNURLPayResponse2{
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: statusError,
Reason: fmt.Sprintf("Invalid user.")},
@@ -152,7 +145,7 @@ func (w Server) serveLNURLpSecond(username string, amount int64, comment string)
// user is ok now create invoice
// set wallet lnbits client
var resp *lnurl.LNURLPayResponse2
var resp *lnurl.LNURLPayValues
// the same description_hash needs to be built in the second request
metadata := w.metaData(username)
@@ -162,35 +155,45 @@ 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)
resp = &lnurl.LNURLPayResponse2{
err = fmt.Errorf("[serveLNURLpSecond] Couldn't create invoice: %v", err.Error())
resp = &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: statusError,
Reason: "Couldn't create invoice."},
}
return resp, err
}
// save invoice struct for later use
invoiceStruct := &telegram.Invoice{
PaymentRequest: invoice.PaymentRequest,
PaymentHash: invoice.PaymentHash,
Amount: amount_msat / 1000,
}
// save lnurl invoice struct for later use (will hold the comment or other 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.LNURLPayResponse2{
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{Status: statusOk},
PR: invoice.PaymentRequest,
Routes: make([][]lnurl.RouteInfo, 0),
Routes: make([]struct{}, 0),
SuccessAction: &lnurl.SuccessAction{Message: "Payment received!", Tag: "message"},
}, nil
@@ -198,11 +201,7 @@ func (w Server) serveLNURLpSecond(username string, amount int64, comment string)
// descriptionHash is the SHA256 hash of the metadata
func (w Server) descriptionHash(metadata lnurl.Metadata) (string, error) {
jsonMeta, err := json.Marshal(metadata)
if err != nil {
return "", err
}
hash := sha256.Sum256([]byte(string(jsonMeta)))
hash := sha256.Sum256([]byte(metadata.Encode()))
hashString := hex.EncodeToString(hash[:])
return hashString, nil
}
@@ -211,6 +210,7 @@ func (w Server) descriptionHash(metadata lnurl.Metadata) (string, error) {
// and is used again in the second response to verify the description hash
func (w Server) metaData(username string) lnurl.Metadata {
return lnurl.Metadata{
{"text/identifier", fmt.Sprintf("%s@%s", username, w.callbackHostname.Hostname())},
{"text/plain", fmt.Sprintf("Pay to %s@%s", username, w.callbackHostname.Hostname())}}
Description: fmt.Sprintf("Pay to %s@%s", username, w.callbackHostname.Hostname()),
LightningAddress: fmt.Sprintf("%s@%s", username, w.callbackHostname.Hostname()),
}
}
+5 -6
View File
@@ -3,7 +3,6 @@ package price
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
@@ -63,7 +62,7 @@ func (p *PriceWatcher) Watch() error {
for currency, _ := range p.Currencies {
avg_price := 0.0
n_responses := 0
for exchange, getPrice := range p.Exchanges {
for _, getPrice := range p.Exchanges {
fprice, err := getPrice(currency)
if err != nil {
// log.Debug(err)
@@ -72,11 +71,11 @@ func (p *PriceWatcher) Watch() error {
}
n_responses++
avg_price += fprice
log.Debugf("[PriceWatcher] %s %s price: %f", exchange, currency, fprice)
// log.Debugf("[PriceWatcher] %s %s price: %f", exchange, currency, fprice)
time.Sleep(time.Second * time.Duration(2))
}
Price[currency] = avg_price / float64(n_responses)
log.Debugf("[PriceWatcher] Average %s price: %f", currency, Price[currency])
// log.Debugf("[PriceWatcher] Average %s price: %f", currency, Price[currency])
}
time.Sleep(p.UpdateInterval)
}
@@ -85,7 +84,7 @@ func (p *PriceWatcher) Watch() error {
func (p *PriceWatcher) GetCoinbasePrice(currency string) (float64, error) {
coinbaseEndpoint, err := url.Parse(fmt.Sprintf("https://api.coinbase.com/v2/prices/spot?currency=%s", currency))
response, err := p.client.Get(coinbaseEndpoint.String())
if err, ok := err.(net.Error); ok && err.Timeout() {
if err != nil {
return 0, err
}
bodyBytes, err := ioutil.ReadAll(response.Body)
@@ -111,7 +110,7 @@ func (p *PriceWatcher) GetBitfinexPrice(currency string) (float64, error) {
pair := bitfinexCurrencyToPair[currency]
bitfinexEndpoint, err := url.Parse(fmt.Sprintf("https://api.bitfinex.com/v1/pubticker/%s", pair))
response, err := p.client.Get(bitfinexEndpoint.String())
if err, ok := err.(net.Error); ok && err.Timeout() {
if err != nil {
return 0, err
}
bodyBytes, err := ioutil.ReadAll(response.Body)
+94
View File
@@ -0,0 +1,94 @@
package rate
import (
"context"
log "github.com/sirupsen/logrus"
"strconv"
"sync"
"golang.org/x/time/rate"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
// Limiter
type Limiter struct {
keys map[string]*rate.Limiter
mu *sync.RWMutex
r rate.Limit
b int
}
var idLimiter *Limiter
var globalLimiter *rate.Limiter
// NewLimiter creates both chat and global rate limiters.
func Start() {
idLimiter = newIdRateLimiter(rate.Limit(0.29), 19)
globalLimiter = rate.NewLimiter(rate.Limit(30), 30)
}
// NewRateLimiter .
func newIdRateLimiter(r rate.Limit, b int) *Limiter {
i := &Limiter{
keys: make(map[string]*rate.Limiter),
mu: &sync.RWMutex{},
r: r,
b: b,
}
return i
}
func CheckLimit(to interface{}) {
globalLimiter.Wait(context.Background())
var id string
switch to.(type) {
case string:
id = to.(string)
case *tb.Chat:
id = strconv.FormatInt(to.(*tb.Chat).ID, 10)
case *tb.User:
id = strconv.FormatInt(to.(*tb.User).ID, 10)
case tb.Recipient:
id = to.(tb.Recipient).Recipient()
case *tb.Message:
if to.(*tb.Message).Chat != nil {
id = strconv.FormatInt(to.(*tb.Message).Chat.ID, 10)
}
}
if len(id) > 0 {
log.Tracef("[Check Limit] limiter for %+v", id)
idLimiter.GetLimiter(id).Wait(context.Background())
return
}
log.Tracef("[Check Limit] skipping id limiter for %+v", to)
}
// Add creates a new rate limiter and adds it to the keys map,
// using the key
func (i *Limiter) Add(key string) *rate.Limiter {
i.mu.Lock()
defer i.mu.Unlock()
limiter := rate.NewLimiter(i.r, i.b)
i.keys[key] = limiter
return limiter
}
// GetLimiter returns the rate limiter for the provided key if it exists.
// Otherwise, calls Add to add key address to the map
func (i *Limiter) GetLimiter(key string) *rate.Limiter {
i.mu.Lock()
limiter, exists := i.keys[key]
if !exists {
i.mu.Unlock()
return i.Add(key)
}
i.mu.Unlock()
return limiter
}
+89
View File
@@ -0,0 +1,89 @@
package runtime
import (
cmap "github.com/orcaman/concurrent-map"
"sync"
"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
Quit chan struct{}
Wg sync.WaitGroup
}
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),
Quit: make(chan struct{}, 1),
Wg: sync.WaitGroup{},
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) DoWait(f func()) {
t.Do(f)
t.Wg.Wait()
}
func (t *ResettableFunctionTicker) Do(f func()) {
t.Started = true
tickerMap.Set(t.name, t)
t.Wg.Add(1)
go func() {
defer t.Wg.Done()
for {
select {
case <-t.Quit:
return
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)
}
}
}()
}
+113
View File
@@ -0,0 +1,113 @@
package mutex
import (
"context"
"fmt"
"github.com/gorilla/mux"
"net/http"
"sync"
cmap "github.com/orcaman/concurrent-map"
log "github.com/sirupsen/logrus"
)
var mutexMap cmap.ConcurrentMap
func init() {
mutexMap = cmap.New()
}
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(fmt.Sprintf("Current number of locks: %d\nLocks: %+v\nUse /mutex/unlock endpoint to unlock all users", len(mutexMap.Keys()), mutexMap.Keys())))
}
func UnlockHTTP(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
if m, ok := mutexMap.Get(vars["id"]); ok {
m.(*sync.Mutex).Unlock()
w.Write([]byte(fmt.Sprintf("Unlocked %s mutexe.\nCurrent number of locks: %d\nLocks: %+v",
vars["id"], len(mutexMap.Keys()), mutexMap.Keys())))
return
}
w.Write([]byte(fmt.Sprintf("Mutex %s not found!", vars["id"])))
}
// checkSoftLock checks in mutexMap how often an existing mutex was already SoftLocked.
// The counter is there to avoid multiple recursive locking of an object in the mutexMap.
// This happens if multiple handlers call each other and try to lock/unlock multiple times
// the same mutex.
func checkSoftLock(s string) int {
if v, ok := mutexMap.Get(fmt.Sprintf("nLocks:%s", s)); ok {
return v.(int)
}
return 0
}
// LockWithContext locks a mutex only if it hasn't been locked before in a context.
// LockWithContext should be used to lock objects like faucets etc.
// The context carries a uid that is unique the each request (message, button press, etc.).
// If the uid has a lock already *for a certain object*, it increments the
// nLocks in the mutexMap. If not, it locks the object. This is supposed to lock only if nLock == 0.
func LockWithContext(ctx context.Context, s string) {
uid := ctx.Value("uid").(string)
// 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)
mutexMap.Remove(fmt.Sprintf("nLocks:%s", uid))
} else {
log.Tracef("[Mutex] Skip unlock (nLocks: %d)", nLocks)
}
Unlock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
//mutexMap.Remove(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
}
// Lock locks a mutex in the mutexMap. If the mutex is already in the map, it locks the current call.
// After it another call unlocks the mutex (and deletes it from the mutexMap) the mutex written again into the mutexMap.
// If the mutex was not in the mutexMap before, a new mutext is created and locked and written into the mutexMap.
func Lock(s string) {
log.Tracef("[Mutex] Attempt Lock %s", s)
if m, ok := mutexMap.Get(s); ok {
m.(*sync.Mutex).Lock()
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("[Once] %s already consumed object", k2)
}
objectMap.Set(k2, true)
return nil
}
// Remove removes the key k1 from the map. Should be called after Once was called and
// the object k1 finished.
func Remove(k1 string) {
onceMap.Remove(k1)
log.Tracef("[Once] Removed key %s from onceMap (len=%d)", k1, len(onceMap.Keys()))
}
+93
View File
@@ -0,0 +1,93 @@
package storage
import (
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"time"
"github.com/eko/gocache/store"
gocache "github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
)
var transactionCache = store.NewGoCache(gocache.New(5*time.Minute, 10*time.Minute), nil)
type Base struct {
ID string `json:"id"`
Active bool `json:"active"`
Canceled bool `json:"canceled"`
CreatedAt time.Time `json:"created"`
UpdatedAt time.Time `json:"updated"`
}
type Option func(b *Base)
func ID(id string) Option {
return func(btx *Base) {
btx.ID = id
}
}
func New(opts ...Option) *Base {
btx := &Base{
Active: true,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
for _, opt := range opts {
opt(btx)
}
return btx
}
func (tx Base) Key() string {
return tx.ID
}
func (tx *Base) Inactivate(s Storable, db *DB) error {
tx.Active = false
err := tx.Set(s, db)
if err != nil {
log.Tracef("[Bunt Inactivate] %s Error: %s", tx.ID, err.Error())
return err
}
log.Tracef("[Bunt Inactivate] %s", tx.ID)
return nil
}
func (tx *Base) Get(s Storable, db *DB) (Storable, error) {
cacheTx, err := transactionCache.Get(s.Key())
if err != nil {
err := db.Get(s)
if err != nil {
return s, err
}
log.Tracef("[Bunt] get object %s", s.Key())
return s, transactionCache.Set(s.Key(), s, &store.Options{Expiration: 5 * time.Minute})
}
log.Tracef("[Bunt Cache] get object %s", s.Key())
return cacheTx.(Storable), err
}
func (tx *Base) Set(s Storable, db *DB) error {
tx.UpdatedAt = time.Now()
err := db.Set(s)
if err != nil {
log.Errorf("[Bunt] could not set object: %v", err.Error())
return err
}
log.Tracef("[Bunt] set object %s", s.Key())
err = transactionCache.Set(s.Key(), s, &store.Options{Expiration: 5 * time.Minute})
if err != nil {
log.Errorf("[Bunt Cache] could not set object: %v", err.Error())
}
log.Tracef("[Bunt Cache] set object: %s", s.Key())
return err
}
func (tx *Base) Delete(s Storable, db *DB) error {
tx.UpdatedAt = time.Now()
runtime.IgnoreError(transactionCache.Delete(s.Key()))
return db.Delete(s.Key(), s)
}
+23 -15
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 * 10)
for tx.InTransaction {
select {
case <-ticker.C:
return nil, fmt.Errorf("transaction timeout")
default:
time.Sleep(time.Duration(500) * time.Millisecond)
err = db.Get(s)
}
}
if err != nil {
return nil, fmt.Errorf("could not get transaction")
}
return s, nil
}
func (tx *Base) Set(s storage.Storable, db *storage.DB) error {
tx.UpdatedAt = time.Now()
return db.Set(s)
}
+38 -12
View File
@@ -8,12 +8,14 @@ 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/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func getArgumentFromCommand(input string, which int) (output string, err error) {
@@ -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
}
@@ -98,16 +100,16 @@ func (bot *TipBot) askForAmount(ctx context.Context, id string, eventType string
AmountMax: amountMax,
OiringalCommand: originalCommand,
}
// set LNURLPayResponse1 in the state of the user
// set LNURLPayParams in the state of the user
stateDataJson, err := json.Marshal(enterAmountStateData)
if err != nil {
log.Errorln(err)
return
}
SetUserState(user, bot, lnbits.UserEnterAmount, string(stateDataJson))
askAmountText := Translate(ctx, "lnurlEnterAmountMessage")
askAmountText := Translate(ctx, "enterAmountMessage")
if amountMin > 0 && amountMax >= amountMin {
askAmountText = fmt.Sprintf(Translate(ctx, "lnurlEnterAmountRangeMessage"), enterAmountStateData.AmountMin/1000, enterAmountStateData.AmountMax/1000)
askAmountText = fmt.Sprintf(Translate(ctx, "enterAmountRangeMessage"), enterAmountStateData.AmountMin/1000, enterAmountStateData.AmountMax/1000)
}
// Let the user enter an amount and return
bot.trySendMessage(user.Telegram, askAmountText, tb.ForceReply)
@@ -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
@@ -176,6 +180,28 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
bot.lnurlPayHandlerSend(ctx, m)
return
case "LnurlWithdrawState":
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(EnterAmountStateData.ID))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
return
}
LnurlWithdrawState := sn.(*LnurlWithdrawState)
LnurlWithdrawState.Amount = amount * 1000 // mSat
// add result to persistent struct
runtime.IgnoreError(LnurlWithdrawState.Set(LnurlWithdrawState, bot.Bunt))
EnterAmountStateData.Amount = int64(amount) * 1000 // mSat
StateDataJson, err := json.Marshal(EnterAmountStateData)
if err != nil {
log.Errorln(err)
return
}
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
bot.lnurlWithdrawHandlerWithdraw(ctx, m)
return
case "CreateInvoiceState":
m.Text = fmt.Sprintf("/invoice %d", amount)
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
+6 -3
View File
@@ -6,12 +6,15 @@ import (
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func (bot TipBot) balanceHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) balanceHandler(ctx context.Context, m *tb.Message) {
// check and print all commands
bot.anyTextHandler(ctx, m)
if len(m.Text) > 0 {
bot.anyTextHandler(ctx, m)
}
// reply only in private message
if m.Chat.Type != tb.ChatPrivate {
// delete message
+15 -6
View File
@@ -2,26 +2,30 @@ package telegram
import (
"fmt"
"github.com/eko/gocache/store"
"sync"
"time"
limiter "github.com/LightningTipBot/LightningTipBot/internal/rate"
"github.com/eko/gocache/store"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
gocache "github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
"gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
"gorm.io/gorm"
)
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
}
type Cache struct {
@@ -39,11 +43,13 @@ func NewBot() TipBot {
gocacheStore := store.NewGoCache(gocacheClient, nil)
// create sqlite databases
db, txLogger := AutoMigration()
limiter.Start()
return 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},
}
@@ -76,13 +82,16 @@ 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()
if err != nil {
log.Errorf("Could not initialize bot wallet: %s", err.Error())
}
bot.startEditWorker()
bot.registerTelegramHandlers()
initInvoiceEventCallbacks(bot)
initializeStateCallbackMessage(bot)
bot.Telegram.Start()
}
+109
View File
@@ -0,0 +1,109 @@
package telegram
import (
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
// we can't use space in the label of buttons, because string splitting will mess everything up.
const (
MainMenuCommandSend = "💸 Send"
MainMenuCommandBalance = "Balance"
MainMenuCommandInvoice = "⚡️ Invoice"
MainMenuCommandHelp = "📖 Help"
)
var (
mainMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
btnHelpMainMenu = mainMenu.Text(MainMenuCommandHelp)
btnSendMainMenu = mainMenu.Text(MainMenuCommandSend)
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
btnInvoiceMainMenu = mainMenu.Text(MainMenuCommandInvoice)
)
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
}
// mainMenuBalanceButtonUpdate updates the balance button in the mainMenu
func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
var user *lnbits.User
var err error
if user, err = getCachedUser(&tb.User{ID: to}, *bot); err != nil {
user, err = GetLnbitsUser(&tb.User{ID: to}, *bot)
if err != nil {
return
}
updateCachedUser(user, *bot)
}
if user.Wallet != nil {
amount, err := bot.GetUserBalanceCached(user)
if err == nil {
log.Debugf("[appendMainMenu] user %s balance %d sat", GetUserStr(user.Telegram), amount)
MainMenuCommandBalance := fmt.Sprintf("%s %d sat", MainMenuCommandBalance, amount)
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu, btnHelpMainMenu),
)
}
}
}
// appendMainMenu will check if to (recipient) ID is from private or group chat.
// appendMainMenu is called in telegram.go every time a user receives a PM from the bot.
// this function will only add a keyboard if this is a private chat and no force reply.
func (bot *TipBot) appendMainMenu(to int64, recipient interface{}, options []interface{}) []interface{} {
// update the balance button
if to > 0 {
bot.mainMenuBalanceButtonUpdate(to)
}
appendKeyboard := true
for _, option := range options {
if option == tb.ForceReply {
appendKeyboard = false
}
switch option.(type) {
case *tb.ReplyMarkup:
appendKeyboard = false
//option.(*tb.ReplyMarkup).ReplyKeyboard = mainMenu.ReplyKeyboard
//if option.(*tb.ReplyMarkup).InlineKeyboard == nil {
// options = append(options[:i], options[i+1:]...)
//}
}
}
// to > 0 is private chats
if to > 0 && appendKeyboard {
options = append(options, mainMenu)
}
return options
}
+12 -7
View File
@@ -2,11 +2,12 @@ package telegram
import (
"fmt"
"github.com/eko/gocache/store"
"reflect"
"strconv"
"time"
"github.com/eko/gocache/store"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/database"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
@@ -15,7 +16,7 @@ import (
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
@@ -25,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 {
@@ -79,6 +80,10 @@ func AutoMigration() (db *gorm.DB, txLogger *gorm.DB) {
func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.User, error) {
toUserDb := &lnbits.User{}
// return error if username is too long
if len(toUserStrWithoutAt) > 100 {
return nil, fmt.Errorf("[GetUserByTelegramUsername] Telegram username is too long: %s..", toUserStrWithoutAt[:100])
}
tx := bot.Database.Where("telegram_username = ? COLLATE NOCASE", toUserStrWithoutAt).First(toUserDb)
if tx.Error != nil || toUserDb.Wallet == nil {
err := tx.Error
@@ -90,7 +95,7 @@ func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.U
return toUserDb, nil
}
func getCachedUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
user := &lnbits.User{Name: strconv.Itoa(u.ID)}
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
if us, err := bot.Cache.Get(user.Name); err == nil {
return us.(*lnbits.User), nil
}
@@ -105,7 +110,7 @@ func getCachedUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
// &tb.User{ID: toId, Username: username}
// without updating the user in storage.
func GetLnbitsUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
user := &lnbits.User{Name: strconv.Itoa(u.ID)}
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
tx := bot.Database.First(user)
if tx.Error != nil {
errmsg := fmt.Sprintf("[GetUser] Couldn't fetch %s from Database: %s", GetUserStr(u), tx.Error.Error())
@@ -158,7 +163,7 @@ func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
log.Errorln(errmsg)
return tx.Error
}
log.Debugf("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
log.Tracef("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
if bot.Cache.GoCacheStore != nil {
updateCachedUser(user, bot)
}
+2 -2
View File
@@ -12,7 +12,7 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
// PLEASE DO NOT CHANGE THE CODE IN THIS FILE
@@ -48,7 +48,7 @@ func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) {
}
// command is valid
msg := bot.trySendMessage(user.Telegram, Translate(ctx, "donationProgressMessage"))
msg := bot.trySendMessage(m.Chat, Translate(ctx, "donationProgressMessage"))
// get invoice
resp, err := http.Get(fmt.Sprintf(donationEndpoint, amount, GetUserStr(user.Telegram), GetUserStr(bot.Telegram.Me)))
if err != nil {
+73
View File
@@ -0,0 +1,73 @@
package telegram
import (
"fmt"
cmap "github.com/orcaman/concurrent-map"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
"time"
)
var editStack cmap.ConcurrentMap
type edit struct {
to tb.Editable
what interface{}
options []interface{}
lastEdit time.Time
edited bool
}
func init() {
editStack = cmap.New()
}
const resultTrueError = "telebot: result is True"
// startEditWorker will loop through the editStack and run tryEditMessage on not edited messages.
// if editFromStack is older than 5 seconds, editFromStack will be removed.
func (bot TipBot) startEditWorker() {
go func() {
for {
for _, k := range editStack.Keys() {
if e, ok := editStack.Get(k); ok {
editFromStack := e.(edit)
if !editFromStack.edited {
_, err := bot.tryEditMessage(editFromStack.to, editFromStack.what, editFromStack.options...)
if err != nil && err.Error() != resultTrueError {
return
}
log.Tracef("[startEditWorker] message from stack edited %+v", editFromStack)
editFromStack.lastEdit = time.Now()
editFromStack.edited = true
editStack.Set(k, editFromStack)
} else {
if editFromStack.lastEdit.Before(time.Now().Add(-(time.Duration(5) * time.Second))) {
log.Tracef("[startEditWorker] removing message edit from stack %+v", editFromStack)
editStack.Remove(k)
}
}
}
}
time.Sleep(time.Second)
}
}()
}
// tryEditStack will add the editable to the edit stack, if what (message) changed.
func (bot TipBot) tryEditStack(to tb.Editable, what interface{}, options ...interface{}) {
msgSig, chat := to.MessageSig()
var sig = fmt.Sprintf("%s-%d", msgSig, chat)
if e, ok := editStack.Get(sig); ok {
editFromStack := e.(edit)
if editFromStack.what == what.(string) {
log.Tracef("[tryEditMessage] message did not change, not attempting to edit")
return
}
}
e := edit{options: options, what: what, to: to}
editStack.Set(sig, e)
}
@@ -3,31 +3,38 @@ 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"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
var (
inlineFaucetMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
btnCancelInlineFaucet = inlineFaucetMenu.Data("🚫 Cancel", "cancel_faucet_inline")
btnAcceptInlineFaucet = inlineFaucetMenu.Data("✅ Collect", "confirm_faucet_inline")
btnAcceptInlineFaucet = inlineFaucetMenu.Data("✅ Start", "confirm_faucet_inline")
)
type InlineFaucet struct {
*transaction.Base
*storage.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"`
Amount int64 `json:"inline_faucet_amount"`
RemainingAmount int64 `json:"inline_faucet_remainingamount"`
PerUserAmount int64 `json:"inline_faucet_peruseramount"`
From *lnbits.User `json:"inline_faucet_from"`
To []*lnbits.User `json:"inline_faucet_to"`
Memo string `json:"inline_faucet_memo"`
@@ -58,10 +65,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)
@@ -70,7 +77,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,7 +89,7 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
id := fmt.Sprintf("inl-faucet-%d-%d-%s", sender.ID, amount, RandStringRunes(5))
return &InlineFaucet{
Base: transaction.New(transaction.ID(id)),
Base: storage.New(storage.ID(id)),
Message: inlineMessage,
Amount: amount,
From: fromUser,
@@ -181,19 +188,25 @@ func (bot TipBot) faucetHandler(ctx context.Context, m *tb.Message) {
ctx = bot.mapFaucetLanguage(ctx, m.Text)
inlineFaucet, err := bot.makeFaucet(ctx, m, false)
if err != nil {
log.Errorf("[faucet] %s", err)
log.Warnf("[faucet] %s", err.Error())
return
}
fromUserStr := GetUserStr(m.Sender)
bot.trySendMessage(m.Chat, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
mFaucet := bot.trySendMessage(m.Chat, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
log.Infof("[faucet] %s created faucet %s: %d sat (%d per user)", fromUserStr, inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
// log faucet link if possible
if mFaucet != nil && mFaucet.Chat != nil {
log.Infof("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(mFaucet.Chat.ID, 10)[4:], mFaucet.ID)
}
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
}
func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
inlineFaucet, err := bot.makeQueryFaucet(ctx, q, false)
if err != nil {
// log.Errorf("[faucet] %s", err)
log.Errorf("[handleInlineFaucetQuery] %s", err.Error())
return
}
urls := []string{
@@ -214,8 +227,8 @@ func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
// needed to set a unique string ID for each result
results[i].SetResultID(inlineFaucet.ID)
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
log.Infof("[faucet] %s created inline faucet %s: %d sat (%d per user)", GetUserStr(inlineFaucet.From.Telegram), inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
bot.Cache.Set(inlineFaucet.ID, inlineFaucet, &store.Options{Expiration: 5 * time.Minute})
log.Infof("[faucet] %s:%d created inline faucet %s: %d sat (%d per user)", GetUserStr(inlineFaucet.From.Telegram), inlineFaucet.From.Telegram.ID, inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
}
err = bot.Telegram.Answer(q, &tb.QueryResponse{
@@ -223,33 +236,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) {
to := LoadUser(ctx)
tx := &InlineFaucet{Base: transaction.New(transaction.ID(c.Data))}
tx := &InlineFaucet{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[faucet] %s", err)
log.Debugf("[acceptInlineFaucetHandler] %s", err.Error())
return
}
inlineFaucet := fn.(*InlineFaucet)
from := inlineFaucet.From
err = inlineFaucet.Lock(inlineFaucet, bot.Bunt)
if err != nil {
log.Errorf("[faucet] LockFaucet %s error: %s", inlineFaucet.ID, err)
return
// log faucet link if possible
if c.Message != nil && c.Message.Chat != nil {
log.Infof("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(c.Message.Chat.ID, 10)[4:], c.Message.ID)
}
if !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
}
@@ -257,11 +272,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)
@@ -270,7 +287,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)
@@ -291,23 +307,23 @@ 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: %d sat from %s to %s ", inlineFaucet.ID, inlineFaucet.PerUserAmount, fromUserStr, toUserStr)
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.Errorln(errmsg)
return
}
go func() {
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineFaucetReceivedMessage"), fromUserStrMd, inlineFaucet.PerUserAmount))
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineFaucetSentMessage"), inlineFaucet.PerUserAmount, toUserStrMd))
}()
// build faucet message
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetMessage"), inlineFaucet.PerUserAmount, inlineFaucet.RemainingAmount, inlineFaucet.Amount, inlineFaucet.NTaken, inlineFaucet.NTotal, MakeProgressbar(inlineFaucet.RemainingAmount, inlineFaucet.Amount))
@@ -320,34 +336,57 @@ 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.tryEditStack(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 := &InlineFaucet{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[cancelInlineSendHandler] %s", err)
log.Debugf("[cancelInlineFaucetHandler] %s", err.Error())
return
}
inlineFaucet := fn.(*InlineFaucet)
if c.Sender.ID == inlineFaucet.From.Telegram.ID {
bot.tryEditMessage(c.Message, i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage"), &tb.ReplyMarkup{})
if ignoreID || c.Sender.ID == inlineFaucet.From.Telegram.ID {
bot.tryEditStack(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 *InlineFaucet) {
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetEndedMessage"), inlineFaucet.Amount, inlineFaucet.NTaken)
if inlineFaucet.UserNeedsWallet {
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
}
bot.tryEditStack(c.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
}
+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)
runtime.RemoveTicker(user.ID)
})
} else {
ticker.ResetChan <- struct{}{}
}
c(ctx, m)
return
}
}
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"context"
"fmt"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func (bot TipBot) makeHelpMessage(ctx context.Context, m *tb.Message) string {
+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))
+24 -2
View File
@@ -3,13 +3,17 @@ package telegram
import (
"context"
"fmt"
"reflect"
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
i18n2 "github.com/nicksnyder/go-i18n/v2/i18n"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
const queryImage = "https://avatars.githubusercontent.com/u/88730856?v=4"
@@ -91,8 +95,23 @@ 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) {
fmt.Printf(q.Query)
// 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.Error())
return
}
switch inlineObject.(type) {
case storage.Storable:
// persist inline object in bunt
runtime.IgnoreError(bot.Bunt.Set(inlineObject.(storage.Storable)))
default:
log.Errorf("[anyChosenInlineHandler] invalid inline object type: %s, query: %s", reflect.TypeOf(inlineObject).String(), q.Query)
}
}
func (bot TipBot) commandTranslationMap(ctx context.Context, command string) context.Context {
@@ -127,6 +146,9 @@ func (bot TipBot) anyQueryHandler(ctx context.Context, q *tb.Query) {
if strings.HasPrefix(q.Text, "send") || strings.HasPrefix(q.Text, "pay") {
bot.handleInlineSendQuery(ctx, q)
}
if strings.HasPrefix(q.Text, "volcano") {
//bot.handleInlineVolcanoQuery(ctx, q)
}
if strings.HasPrefix(q.Text, "faucet") || strings.HasPrefix(q.Text, "zapfhahn") || strings.HasPrefix(q.Text, "kraan") || strings.HasPrefix(q.Text, "grifo") {
if len(strings.Split(q.Text, " ")) > 1 {
+152 -48
View File
@@ -1,17 +1,24 @@
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"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
var (
@@ -21,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"`
@@ -38,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
}
@@ -112,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,
@@ -121,7 +130,7 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
From_SpecificUser: from_SpecificUser,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
bot.Cache.Set(inlineReceive.ID, inlineReceive, &store.Options{Expiration: 5 * time.Minute})
}
err = bot.Telegram.Answer(q, &tb.QueryResponse{
@@ -135,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 {
@@ -171,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 {
@@ -206,41 +248,104 @@ 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("[acceptInlineReceiveHandler] %d sat from %s to %s", inlineReceive.Amount, fromUserStr, toUserStr)
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))
memo := inlineReceive.Memo
if len(memo) > 0 {
inlineReceive.Message = inlineReceive.Message + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveAppendMemo"), memo)
func (bot *TipBot) inlineReceiveInvoice(ctx context.Context, c *tb.Callback, inlineReceive *InlineReceive) {
if !inlineReceive.Active {
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
return
}
if !to.Initialized {
inlineReceive.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
}
bot.tryEditMessage(c.Message, inlineReceive.Message, &tb.ReplyMarkup{})
// notify users
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, inlineReceive.Amount))
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), inlineReceive.Amount, toUserStrMd))
invoice, err := bot.createInvoiceWithEvent(ctx, inlineReceive.To, inlineReceive.Amount, fmt.Sprintf("Pay to %s", GetUserStr(inlineReceive.To.Telegram)), InvoiceCallbackInlineReceive, inlineReceive.ID)
if err != nil {
errmsg := fmt.Errorf("[acceptInlineReceiveHandler] Error: Receive message to %s: %s", toUserStr, err)
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
bot.tryEditMessage(inlineReceive.Message, Translate(ctx, "errorTryLaterMessage"))
log.Errorln(errmsg)
return
}
// 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.MessageText += fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveAppendMemo"), memo)
}
if !to.Initialized {
inlineReceive.MessageText += "\n\n" + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
}
bot.tryEditMessage(inlineReceive.Message, inlineReceive.MessageText, &tb.ReplyMarkup{})
// notify users
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, inlineReceive.Amount))
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), inlineReceive.Amount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[acceptInlineReceiveHandler] Error: Receive message to %s: %s", toUserStr, err)
log.Warnln(errmsg)
}
// 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)
@@ -248,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
+26 -25
View File
@@ -4,15 +4,20 @@ import (
"context"
"fmt"
"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"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
var (
@@ -22,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"`
@@ -129,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,
@@ -140,7 +145,7 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
}
// add result to persistent struct
runtime.IgnoreError(inlineSend.Set(inlineSend, bot.Bunt))
bot.Cache.Set(inlineSend.ID, inlineSend, &store.Options{Expiration: 5 * time.Minute})
}
err = bot.Telegram.Answer(q, &tb.QueryResponse{
@@ -155,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
@@ -221,13 +222,13 @@ 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
}
log.Infof("[sendInline] %d sat from %s to %s", amount, fromUserStr, toUserStr)
log.Infof("[💸 sendInline] Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
inlineSend.Message = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineSend.LanguageCode, "inlineSendUpdateMessageAccept"), amount, fromUserStrMd, toUserStrMd))
memo := inlineSend.Memo
@@ -239,21 +240,22 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
}
bot.tryEditMessage(c.Message, inlineSend.Message, &tb.ReplyMarkup{})
// notify users
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
_, err = bot.Telegram.Send(fromUser.Telegram, fmt.Sprintf(i18n.Translate(fromUser.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
bot.trySendMessage(fromUser.Telegram, fmt.Sprintf(i18n.Translate(fromUser.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[sendInline] Error: Send message to %s: %s", toUserStr, err)
log.Errorln(errmsg)
return
log.Warnln(errmsg)
}
}
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)
@@ -261,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
+35 -35
View File
@@ -4,15 +4,20 @@ import (
"context"
"fmt"
"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"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
var (
@@ -22,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"`
@@ -59,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
@@ -68,7 +73,7 @@ func (bot TipBot) createTipjar(ctx context.Context, text string, sender *tb.User
inlineMessage := fmt.Sprintf(
Translate(ctx, "inlineTipjarMessage"),
perUserAmount,
GetUserStr(toUser.Telegram),
GetUserStrMd(toUser.Telegram),
0,
amount,
0,
@@ -80,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,
@@ -159,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...))
@@ -178,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)
@@ -190,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{
@@ -211,7 +216,7 @@ func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) {
// needed to set a unique string ID for each result
results[i].SetResultID(inlineTipjar.ID)
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
bot.Cache.Set(inlineTipjar.ID, inlineTipjar, &store.Options{Expiration: 5 * time.Minute})
log.Infof("[tipjar] %s created inline tipjar %s: %d sat (%d per user)", GetUserStr(inlineTipjar.To.Telegram), inlineTipjar.ID, inlineTipjar.Amount, inlineTipjar.PerUserAmount)
}
@@ -230,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"))
@@ -256,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
@@ -276,29 +276,28 @@ 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
}
log.Infof("[tipjar] tipjar %s: %d sat from %s to %s ", inlineTipjar.ID, inlineTipjar.PerUserAmount, fromUserStr, toUserStr)
log.Infof("[💸 tipjar] Tipjar %s from %s to %s (%d sat).", inlineTipjar.ID, fromUserStr, toUserStr, inlineTipjar.PerUserAmount)
inlineTipjar.NGiven += 1
inlineTipjar.From = append(inlineTipjar.From, from)
inlineTipjar.GivenAmount = inlineTipjar.GivenAmount + inlineTipjar.PerUserAmount
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineTipjarReceivedMessage"), fromUserStrMd, inlineTipjar.PerUserAmount))
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineTipjarSentMessage"), inlineTipjar.PerUserAmount, toUserStrMd))
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineTipjarReceivedMessage"), fromUserStrMd, inlineTipjar.PerUserAmount))
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineTipjarSentMessage"), inlineTipjar.PerUserAmount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[tipjar] Error: Send message to %s: %s", toUserStr, err)
log.Errorln(errmsg)
return
log.Warnln(errmsg)
}
// build tipjar message
inlineTipjar.Message = fmt.Sprintf(
i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarMessage"),
inlineTipjar.PerUserAmount,
GetUserStr(inlineTipjar.To.Telegram),
GetUserStrMd(inlineTipjar.To.Telegram),
inlineTipjar.GivenAmount,
inlineTipjar.Amount,
inlineTipjar.NGiven,
@@ -319,7 +318,7 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
// tipjar is full
inlineTipjar.Message = fmt.Sprintf(
i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarEndedMessage"),
GetUserStr(inlineTipjar.To.Telegram),
GetUserStrMd(inlineTipjar.To.Telegram),
inlineTipjar.Amount,
inlineTipjar.NGiven,
)
@@ -333,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)
@@ -344,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
+10 -2
View File
@@ -3,7 +3,7 @@ package intercept
import (
"context"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type CallbackFuncHandler func(ctx context.Context, message *tb.Callback)
@@ -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 {
+11 -3
View File
@@ -2,8 +2,9 @@ package intercept
import (
"context"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type MessageInterface interface {
@@ -15,6 +16,7 @@ type handlerMessageInterceptor struct {
handler MessageFuncHandler
before MessageChain
after MessageChain
onDefer MessageChain
}
type MessageChain []Func
type MessageInterceptOption func(*handlerMessageInterceptor)
@@ -29,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 {
@@ -47,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 {
+14 -5
View File
@@ -2,8 +2,9 @@ package intercept
import (
"context"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type QueryFuncHandler func(ctx context.Context, message *tb.Query)
@@ -12,6 +13,7 @@ type handlerQueryInterceptor struct {
handler QueryFuncHandler
before QueryChain
after QueryChain
onDefer QueryChain
}
type QueryChain []Func
type QueryInterceptOption func(*handlerQueryInterceptor)
@@ -26,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 {
@@ -48,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
+84 -16
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"
@@ -10,7 +15,7 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type InterceptorType int
@@ -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
}
+116 -13
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/tucnak/telebot.v2"
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,81 @@ 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) {
// do balance check for keyboard update
_, err := bot.GetUserBalance(invoiceEvent.User)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", GetUserStr(invoiceEvent.User.Telegram))
log.Errorln(errmsg)
}
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)))
}
}
}
+21 -5
View File
@@ -4,15 +4,17 @@ import (
"bytes"
"context"
"fmt"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
log "github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func (bot TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
if internal.Configuration.Lnbits.LnbitsPublicUrl == "" {
bot.trySendMessage(m.Sender, Translate(ctx, "couldNotLinkMessage"))
return
@@ -28,16 +30,30 @@ func (bot TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
fromUser := LoadUser(ctx)
bot.trySendMessage(m.Sender, Translate(ctx, "walletConnectMessage"))
// do not respond to banned users
if strings.HasPrefix(fromUser.Wallet.Adminkey, "banned") || strings.HasPrefix(fromUser.Wallet.Adminkey, "_") {
return
}
lndhubUrl := fmt.Sprintf("lndhub://admin:%s@%slndhub/ext/", fromUser.Wallet.Adminkey, internal.Configuration.Lnbits.LnbitsPublicUrl)
// 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 invoice data to user
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
// send the link to the user
linkmsg := bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
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))
}
+63 -52
View File
@@ -9,23 +9,26 @@ 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/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
// LnurlPayState saves the state of the user for an LNURL payment
type LnurlPayState struct {
*transaction.Base
From *lnbits.User `json:"from"`
LNURLPayResponse1 lnurl.LNURLPayResponse1 `json:"LNURLPayResponse1"`
LNURLPayResponse2 lnurl.LNURLPayResponse2 `json:"LNURLPayResponse2"`
Amount int `json:"amount"`
Comment string `json:"comment"`
LanguageCode string `json:"languagecode"`
*storage.Base
From *lnbits.User `json:"from"`
LNURLPayParams lnurl.LNURLPayParams `json:"LNURLPayParams"`
LNURLPayValues lnurl.LNURLPayValues `json:"LNURLPayValues"`
Amount int64 `json:"amount"`
Comment string `json:"comment"`
LanguageCode string `json:"languagecode"`
}
// lnurlPayHandler1 is invoked when the first lnurl response was a lnurlpay response
@@ -37,48 +40,58 @@ 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)),
LNURLPayResponse1: payParams.LNURLPayResponse1,
LanguageCode: ctx.Value("publicLanguageCode").(string),
lnurlPayState := &LnurlPayState{
Base: storage.New(storage.ID(id)),
From: user,
LNURLPayParams: payParams.LNURLPayParams,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
// add result to persistent struct
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
// if no amount is in the command, ask for it
amount, err := decodeAmountFromCommand(m.Text)
if err != nil || amount < 1 {
// // no amount was entered, set user state and ask for amount
bot.askForAmount(ctx, id, "LnurlPayState", lnurlPayState.LNURLPayResponse1.MinSendable, lnurlPayState.LNURLPayResponse1.MaxSendable, m.Text)
return
// first we check whether an amount is present in the command
amount, amount_err := decodeAmountFromCommand(m.Text)
// we need to figure out whether the memo starts at position 2 or 3
// so either /lnurl <amount> <lnurl> [memo] or /lnurl <lnurl> [memo]
memoStartsAt := 2
if amount_err == nil {
// amount was present
memoStartsAt = 3
}
// check if memo is present in command
memo := GetMemoFromCommand(m.Text, memoStartsAt)
// shorten memo to allowed length
if len(memo) > int(lnurlPayState.LNURLPayParams.CommentAllowed) {
memo = memo[:lnurlPayState.LNURLPayParams.CommentAllowed]
}
if len(memo) > 0 {
lnurlPayState.Comment = memo
}
// amount is already present in the command, i.e., /lnurl <amount> <LNURL>
// amount not in allowed range from LNURL
if int64(amount) > (lnurlPayState.LNURLPayResponse1.MaxSendable/1000) || int64(amount) < (lnurlPayState.LNURLPayResponse1.MinSendable/1000) {
err = fmt.Errorf("amount not in range")
if amount_err == nil &&
(int64(amount) > (lnurlPayState.LNURLPayParams.MaxSendable/1000) || int64(amount) < (lnurlPayState.LNURLPayParams.MinSendable/1000)) &&
(lnurlPayState.LNURLPayParams.MaxSendable != 0 && lnurlPayState.LNURLPayParams.MinSendable != 0) { // only if max and min are set
err := fmt.Errorf("amount not in range")
log.Warnf("[lnurlPayHandler] Error: %s", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), lnurlPayState.LNURLPayResponse1.MinSendable/1000, lnurlPayState.LNURLPayResponse1.MaxSendable/1000))
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), lnurlPayState.LNURLPayParams.MinSendable/1000, lnurlPayState.LNURLPayParams.MaxSendable/1000))
ResetUserState(user, bot)
return
}
// set also amount in the state of the user
lnurlPayState.Amount = amount * 1000 // save as mSat
// check if comment is presentin lnrul-p
memo := GetMemoFromCommand(m.Text, 3)
// shorten comment to allowed length
if len(memo) > int(lnurlPayState.LNURLPayResponse1.CommentAllowed) {
memo = memo[:lnurlPayState.LNURLPayResponse1.CommentAllowed]
}
if len(memo) > 0 {
lnurlPayState.Comment = memo
}
// add result to persistent struct
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
// not necessary to save this in the state data, but till doing it
// now we actualy check whether the amount was in the command and if not, ask for it
if amount_err != nil || amount < 1 {
// // no amount was entered, set user state and ask for amount
bot.askForAmount(ctx, id, "LnurlPayState", lnurlPayState.LNURLPayParams.MinSendable, lnurlPayState.LNURLPayParams.MaxSendable, m.Text)
return
}
// We need to save the pay state in the user state so we can load the payment in the next handler
paramsJson, err := json.Marshal(lnurlPayState)
if err != nil {
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
@@ -91,7 +104,7 @@ func (bot *TipBot) lnurlPayHandler(ctx context.Context, m *tb.Message, payParams
return
}
// lnurlPayHandler is invoked when the user has delivered an amount and is ready to pay
// lnurlPayHandlerSend is invoked when the user has delivered an amount and is ready to pay
func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
user := LoadUser(ctx)
if user.Wallet == nil {
@@ -101,7 +114,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
// assert that user has entered an amount
if user.StateKey != lnbits.UserHasEnteredAmount {
log.Errorln("[lnurlPayHandler] state keys don't match")
log.Errorln("[lnurlPayHandlerSend] state keys don't match")
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
@@ -110,16 +123,18 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
var enterAmountData EnterAmountStateData
err := json.Unmarshal([]byte(user.StateData), &enterAmountData)
if err != nil {
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
// use the enter amount state of the user to load the LNURL payment state
tx := &LnurlPayState{Base: transaction.New(transaction.ID(enterAmountData.ID))}
tx := &LnurlPayState{Base: storage.New(storage.ID(enterAmountData.ID))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
@@ -129,21 +144,19 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
client, err := bot.GetHttpClient()
if err != nil {
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, err.Error())
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayResponse1.Callback)
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
if err != nil {
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, err.Error())
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
qs := callbackUrl.Query()
// add amount to query string
qs.Set("amount", strconv.Itoa(lnurlPayState.Amount)) // msat
qs.Set("amount", strconv.FormatInt(lnurlPayState.Amount, 10)) // msat
// add comment to query string
if len(lnurlPayState.Comment) > 0 {
qs.Set("comment", lnurlPayState.Comment)
@@ -154,31 +167,29 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
res, err := client.Get(callbackUrl.String())
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
var response2 lnurl.LNURLPayResponse2
var response2 lnurl.LNURLPayValues
json.Unmarshal(body, &response2)
if response2.Status == "ERROR" || len(response2.PR) < 1 {
error_reason := "Could not receive invoice."
if len(response2.Reason) > 0 {
error_reason = response2.Reason
}
log.Errorf("[lnurlPayHandler] Error in LNURLPayResponse2: %s", error_reason)
log.Errorf("[lnurlPayHandler] Error in LNURLPayValues: %s", error_reason)
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
return
}
lnurlPayState.LNURLPayResponse2 = response2
lnurlPayState.LNURLPayValues = response2
// add result to persistent struct
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
bot.Telegram.Delete(statusMsg)
@@ -186,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")
+331
View File
@@ -0,0 +1,331 @@
package telegram
import (
"context"
"encoding/json"
"fmt"
"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/str"
lnurl "github.com/fiatjaf/go-lnurl"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
var (
withdrawConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
btnCancelWithdraw = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_withdraw")
btnWithdraw = paymentConfirmationMenu.Data("✅ Withdraw", "confirm_withdraw")
)
// LnurlWithdrawState saves the state of the user for an LNURL payment
type LnurlWithdrawState struct {
*storage.Base
From *lnbits.User `json:"from"`
LNURLWithdrawResponse lnurl.LNURLWithdrawResponse `json:"LNURLWithdrawResponse"`
LNURResponse lnurl.LNURLResponse `json:"LNURLResponse"`
Amount int64 `json:"amount"`
Comment string `json:"comment"`
LanguageCode string `json:"languagecode"`
Success bool `json:"success"`
Invoice lnbits.BitInvoice `json:"invoice"`
Message string `json:"message"`
}
func (bot *TipBot) editSingleButton(ctx context.Context, m *tb.Message, message string, button string) {
bot.tryEditMessage(
m,
message,
&tb.ReplyMarkup{
InlineKeyboard: [][]tb.InlineButton{
{tb.InlineButton{Text: button}},
},
},
)
}
// lnurlWithdrawHandler is invoked when the first lnurl response was a lnurl-withdraw response
// at this point, the user hans't necessarily entered an amount yet
func (bot *TipBot) lnurlWithdrawHandler(ctx context.Context, m *tb.Message, withdrawParams LnurlWithdrawState) {
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
// object that holds all information about the send payment
id := fmt.Sprintf("lnurlw-%d-%s", m.Sender.ID, RandStringRunes(5))
LnurlWithdrawState := LnurlWithdrawState{
Base: storage.New(storage.ID(id)),
From: user,
LNURLWithdrawResponse: withdrawParams.LNURLWithdrawResponse,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
// first we check whether an amount is present in the command
amount, amount_err := decodeAmountFromCommand(m.Text)
// amount is already present in the command, i.e., /lnurl <amount> <LNURL>
// amount not in allowed range from LNURL
if amount_err == nil &&
(int64(amount) > (LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable/1000) || int64(amount) < (LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable/1000)) &&
(LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable != 0 && LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable != 0) { // only if max and min are set
err := fmt.Errorf("amount not in range")
log.Warnf("[lnurlWithdrawHandler] Error: %s", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable/1000, LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable/1000))
ResetUserState(user, bot)
return
}
// if no amount is entered, and if only one amount is possible, we use it
if amount_err != nil && LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable == LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable {
amount = int64(LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable / 1000)
amount_err = nil
}
// set also amount in the state of the user
LnurlWithdrawState.Amount = amount * 1000 // save as mSat
// add result to persistent struct
runtime.IgnoreError(LnurlWithdrawState.Set(LnurlWithdrawState, bot.Bunt))
// now we actualy check whether the amount was in the command and if not, ask for it
if amount_err != nil || amount < 1 {
// // no amount was entered, set user state and ask for amount
bot.askForAmount(ctx, id, "LnurlWithdrawState", LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable, LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable, m.Text)
return
}
// We need to save the pay state in the user state so we can load the payment in the next handler
paramsJson, err := json.Marshal(LnurlWithdrawState)
if err != nil {
log.Errorf("[lnurlWithdrawHandler] Error: %s", err.Error())
// bot.trySendMessage(m.Sender, err.Error())
return
}
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
// directly go to confirm
bot.lnurlWithdrawHandlerWithdraw(ctx, m)
return
}
// lnurlWithdrawHandlerWithdraw is invoked when the user has delivered an amount and is ready to pay
func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Message) {
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlPreparingWithdraw"))
// assert that user has entered an amount
if user.StateKey != lnbits.UserHasEnteredAmount {
log.Errorln("[lnurlWithdrawHandlerWithdraw] state keys don't match")
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
// read the enter amount state from user.StateData
var enterAmountData EnterAmountStateData
err := json.Unmarshal([]byte(user.StateData), &enterAmountData)
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
// use the enter amount state of the user to load the LNURL payment state
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(enterAmountData.ID))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
var lnurlWithdrawState *LnurlWithdrawState
switch fn.(type) {
case *LnurlWithdrawState:
lnurlWithdrawState = fn.(*LnurlWithdrawState)
default:
log.Errorf("[lnurlWithdrawHandlerWithdraw] invalid type")
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
confirmText := fmt.Sprintf(Translate(ctx, "confirmLnurlWithdrawMessage"), lnurlWithdrawState.Amount/1000)
if len(lnurlWithdrawState.LNURLWithdrawResponse.DefaultDescription) > 0 {
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(lnurlWithdrawState.LNURLWithdrawResponse.DefaultDescription))
}
lnurlWithdrawState.Message = confirmText
// create inline buttons
withdrawButton := paymentConfirmationMenu.Data(Translate(ctx, "withdrawButtonMessage"), "confirm_withdraw")
btnCancelWithdraw := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_withdraw")
withdrawButton.Data = lnurlWithdrawState.ID
btnCancelWithdraw.Data = lnurlWithdrawState.ID
withdrawConfirmationMenu.Inline(
withdrawConfirmationMenu.Row(
withdrawButton,
btnCancelWithdraw),
)
bot.tryEditMessage(statusMsg, confirmText, withdrawConfirmationMenu)
// // add response to persistent struct
// lnurlWithdrawState.LNURResponse = response2
runtime.IgnoreError(lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt))
}
// confirmPayHandler when user clicked pay on payment confirmation
func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) {
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[confirmWithdrawHandler] Error: %s", err.Error())
return
}
var lnurlWithdrawState *LnurlWithdrawState
switch fn.(type) {
case *LnurlWithdrawState:
lnurlWithdrawState = fn.(*LnurlWithdrawState)
default:
log.Errorf("[confirmWithdrawHandler] invalid type")
return
}
// onnly the correct user can press
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
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.Set(lnurlWithdrawState, bot.Bunt)
user := LoadUser(ctx)
if user.Wallet == nil {
bot.tryDeleteMessage(c.Message)
return
}
// reset state immediately
ResetUserState(user, bot)
// update button text
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlPreparingWithdraw"))
callbackUrl, err := url.Parse(lnurlWithdrawState.LNURLWithdrawResponse.Callback)
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
return
}
// generate an invoice and add the pr to the request
// generate invoice
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Out: false,
Amount: int64(lnurlWithdrawState.Amount) / 1000,
Memo: "Withdraw",
Webhook: internal.Configuration.Lnbits.WebhookServer},
bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[lnurlWithdrawHandlerWithdraw] Could not create an invoice: %s", err.Error())
log.Errorln(errmsg)
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
return
}
lnurlWithdrawState.Invoice = invoice
qs := callbackUrl.Query()
// add amount to query string
qs.Set("pr", invoice.PaymentRequest)
qs.Set("k1", lnurlWithdrawState.LNURLWithdrawResponse.K1)
callbackUrl.RawQuery = qs.Encode()
// lnurlWithdrawState loaded
client, err := bot.GetHttpClient()
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
return
}
res, err := client.Get(callbackUrl.String())
if err != nil || res.StatusCode >= 300 {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Failed.")
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
return
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
return
}
// parse the response
var response2 lnurl.LNURLResponse
json.Unmarshal(body, &response2)
if response2.Status == "OK" {
// update button text
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawSuccess"))
} else {
log.Errorf("[lnurlWithdrawHandlerWithdraw] LNURLWithdraw failed.")
// update button text
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawFailed"))
return
}
// add response to persistent struct
lnurlWithdrawState.LNURResponse = response2
runtime.IgnoreError(lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt))
}
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
func (bot *TipBot) cancelWithdrawHandler(ctx context.Context, c *tb.Callback) {
// reset state immediately
user := LoadUser(ctx)
ResetUserState(user, bot)
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[cancelWithdrawHandler] Error: %s", err.Error())
return
}
var lnurlWithdrawState *LnurlWithdrawState
switch fn.(type) {
case *LnurlWithdrawState:
lnurlWithdrawState = fn.(*LnurlWithdrawState)
default:
log.Errorf("[cancelWithdrawHandler] invalid type")
}
// onnly the correct user can press
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
return
}
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawCancelled"), &tb.ReplyMarkup{})
lnurlWithdrawState.Inactivate(lnurlWithdrawState, bot.Bunt)
}
+81 -160
View File
@@ -11,13 +11,13 @@ import (
"strings"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/tidwall/gjson"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
lnurl "github.com/fiatjaf/go-lnurl"
log "github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode"
"github.com/tidwall/gjson"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func (bot *TipBot) GetHttpClient() (*http.Client, error) {
@@ -55,27 +55,50 @@ func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) {
bot.lnurlReceiveHandler(ctx, m)
return
}
// assume payment
// HandleLNURL by fiatjaf/go-lnurl
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlResolvingUrlMessage"))
_, params, err := bot.HandleLNURL(m.Text)
var lnurlSplit string
split := strings.Split(m.Text, " ")
if _, err := decodeAmountFromCommand(m.Text); err == nil {
// command is /lnurl 123 <LNURL> [memo]
if len(split) > 2 {
lnurlSplit = split[2]
}
} else if len(split) > 1 {
lnurlSplit = split[1]
} else {
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "Could not parse command."))
log.Warnln("[/lnurl] Could not parse command.")
return
}
// get rid of the URI prefix
lnurlSplit = strings.TrimPrefix(lnurlSplit, "lightning:")
// HandleLNURL by fiatjaf/go-lnurl
_, params, err := bot.HandleLNURL(lnurlSplit)
if err != nil {
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), "could not resolve LNURL."))
log.Errorln(err)
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
log.Warnf("[HandleLNURL] Error: %s", err.Error())
return
}
switch params.(type) {
case lnurl.LNURLPayResponse1:
payParams := LnurlPayState{LNURLPayResponse1: params.(lnurl.LNURLPayResponse1)}
log.Infof("[lnurlHandler] %s", payParams.LNURLPayResponse1.Callback)
case 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)}
log.Infof("[LNURL-w] %s", withdrawParams.LNURLWithdrawResponse.Callback)
bot.tryDeleteMessage(statusMsg)
bot.lnurlWithdrawHandler(ctx, m, withdrawParams)
default:
err := fmt.Errorf("invalid LNURL type.")
log.Errorln(err)
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
if err == nil {
err = errors.New("Invalid LNURL type.")
}
log.Warnln(err)
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
// bot.trySendMessage(m.Sender, err.Error())
return
}
@@ -118,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"))
bot.trySendMessage(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
}
@@ -135,131 +158,8 @@ func (bot TipBot) lnurlReceiveHandler(ctx context.Context, m *tb.Message) {
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lnurlEncode)})
}
// // lnurlEnterAmountHandler is invoked if the user didn't deliver an amount for the lnurl payment
// func (bot *TipBot) lnurlEnterAmountHandler(ctx context.Context, m *tb.Message) {
// user := LoadUser(ctx)
// if user.Wallet == nil {
// return
// }
// if user.StateKey == lnbits.UserStateLNURLEnterAmount || user.StateKey == lnbits.UserEnterAmount {
// a, err := strconv.Atoi(m.Text)
// if err != nil {
// log.Errorln(err)
// bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
// ResetUserState(user, bot)
// return
// }
// amount := int64(a)
// var stateResponse LnurlPayState
// err = json.Unmarshal([]byte(user.StateData), &stateResponse)
// if err != nil {
// log.Errorln(err)
// ResetUserState(user, bot)
// return
// }
// // amount not in allowed range from LNURL
// if amount > (stateResponse.LNURLPayResponse1.MaxSendable/1000) || amount < (stateResponse.LNURLPayResponse1.MinSendable/1000) {
// err = fmt.Errorf("amount not in range")
// log.Errorln(err)
// bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), stateResponse.LNURLPayResponse1.MinSendable/1000, stateResponse.LNURLPayResponse1.MaxSendable/1000))
// ResetUserState(user, bot)
// return
// }
// stateResponse.Amount = a
// state, err := json.Marshal(stateResponse)
// if err != nil {
// log.Errorln(err)
// ResetUserState(user, bot)
// return
// }
// SetUserState(user, bot, lnbits.UserStateConfirmLNURLPay, string(state))
// bot.lnurlPayHandler(ctx, m)
// }
// }
// // LnurlStateResponse saves the state of the user for an LNURL payment
// type LnurlStateResponse struct {
// lnurl.LNURLPayResponse1
// Amount int `json:"amount"`
// Comment string `json:"comment"`
// }
// // lnurlPayHandler is invoked when the user has delivered an amount and is ready to pay
// func (bot *TipBot) lnurlPayHandler(ctx context.Context, c *tb.Message) {
// msg := bot.trySendMessage(c.Sender, Translate(ctx, "lnurlGettingUserMessage"))
// user := LoadUser(ctx)
// if user.Wallet == nil {
// return
// }
// if user.StateKey == lnbits.UserStateConfirmLNURLPay {
// client, err := getHttpClient()
// if err != nil {
// log.Errorln(err)
// // bot.trySendMessage(c.Sender, err.Error())
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
// return
// }
// var stateResponse LnurlStateResponse
// err = json.Unmarshal([]byte(user.StateData), &stateResponse)
// if err != nil {
// log.Errorln(err)
// // bot.trySendMessage(c.Sender, err.Error())
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
// return
// }
// callbackUrl, err := url.Parse(stateResponse.Callback)
// if err != nil {
// log.Errorln(err)
// // bot.trySendMessage(c.Sender, err.Error())
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
// return
// }
// qs := callbackUrl.Query()
// // add amount to query string
// qs.Set("amount", strconv.Itoa(stateResponse.Amount*1000))
// // add comment to query string
// if len(stateResponse.Comment) > 0 {
// qs.Set("comment", stateResponse.Comment)
// }
// callbackUrl.RawQuery = qs.Encode()
// res, err := client.Get(callbackUrl.String())
// if err != nil {
// log.Errorln(err)
// // bot.trySendMessage(c.Sender, err.Error())
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
// return
// }
// var response2 lnurl.LNURLPayResponse2
// body, err := ioutil.ReadAll(res.Body)
// if err != nil {
// log.Errorln(err)
// // bot.trySendMessage(c.Sender, err.Error())
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
// return
// }
// json.Unmarshal(body, &response2)
// if len(response2.PR) < 1 {
// error_reason := "Could not receive invoice."
// if len(response2.Reason) > 0 {
// error_reason = response2.Reason
// }
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
// return
// }
// bot.Telegram.Delete(msg)
// c.Text = fmt.Sprintf("/pay %s", response2.PR)
// bot.payHandler(ctx, c)
// }
// }
// from https://github.com/fiatjaf/go-lnurl
func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
// fiatjaf/go-lnurl 1.8.4 with proxy
func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
var err error
var rawurl string
@@ -273,13 +173,24 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
}
} else if strings.HasPrefix(rawlnurl, "http") {
rawurl = rawlnurl
} else if strings.HasPrefix(rawlnurl, "lnurlp://") ||
strings.HasPrefix(rawlnurl, "lnurlw://") ||
strings.HasPrefix(rawlnurl, "lnurla://") ||
strings.HasPrefix(rawlnurl, "keyauth://") {
scheme := "https:"
if strings.Contains(rawurl, ".onion/") || strings.HasSuffix(rawurl, ".onion") {
scheme = "http:"
}
location := strings.SplitN(rawlnurl, ":", 2)[1]
rawurl = scheme + location
} else {
foundUrl, ok := lnurl.FindLNURLInText(rawlnurl)
lnurl_str, ok := lnurl.FindLNURLInText(rawlnurl)
if !ok {
return "", nil,
errors.New("invalid bech32-encoded lnurl: " + rawlnurl)
}
rawurl, err = lnurl.LNURLDecode(foundUrl)
rawurl, err = lnurl.LNURLDecode(lnurl_str)
if err != nil {
return "", nil, err
}
@@ -290,17 +201,24 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
return rawurl, nil, err
}
// query := parsed.Query()
query := parsed.Query()
// switch query.Get("tag") {
// case "login":
// value, err := lnurl.HandleAuth(rawurl, parsed, query)
// return rawurl, value, err
// case "withdrawRequest":
// if value, ok := lnurl.HandleFastWithdraw(query); ok {
// return rawurl, value, nil
// }
switch query.Get("tag") {
case "login":
value, err := lnurl.HandleAuth(rawurl, parsed, query)
return rawurl, value, err
case "withdrawRequest":
if value, ok := lnurl.HandleFastWithdraw(query); ok {
return rawurl, value, nil
}
}
// // original withouth proxy
// resp, err := http.Get(rawurl)
// if err != nil {
// return rawurl, nil, err
// }
client, err := bot.GetHttpClient()
if err != nil {
return "", nil, err
@@ -309,6 +227,9 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
if err != nil {
return rawurl, nil, err
}
if resp.StatusCode >= 300 {
return rawurl, nil, errors.New("HTTP error: " + resp.Status)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
@@ -325,16 +246,16 @@ func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, erro
}
switch j.Get("tag").String() {
// case "withdrawRequest":
// value, err := lnurl.HandleWithdraw(j)
// return rawurl, value, err
case "withdrawRequest":
value, err := lnurl.HandleWithdraw(b)
return rawurl, value, err
case "payRequest":
value, err := lnurl.HandlePay(j)
value, err := lnurl.HandlePay(b)
return rawurl, value, err
// case "channelRequest":
// value, err := lnurl.HandleChannel(j)
// value, err := lnurl.HandleChannel(b)
// return rawurl, value, err
default:
return rawurl, nil, errors.New("unknown response tag " + j.String())
return rawurl, nil, errors.New("Unkown LNURL response.")
}
}
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"strconv"
"time"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type Message struct {
+38 -31
View File
@@ -5,14 +5,17 @@ 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"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
var (
@@ -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"))
@@ -85,23 +88,21 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
return
}
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
// check user balance first
balance, err := bot.GetUserBalance(user)
if err != nil {
NewMessage(m, WithDuration(0, bot))
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err)
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err.Error())
log.Errorln(errmsg)
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
bot.trySendMessage(m.Sender, Translate(ctx, "errorTryLaterMessage"))
return
}
if amount > balance {
NewMessage(m, WithDuration(0, bot))
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "insufficientFundsMessage"), balance, amount))
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "insufficientFundsMessage"), balance, amount))
return
}
bot.tryDeleteMessage(statusMsg)
// send warning that the invoice might fail due to missing fee reserve
if float64(amount) > float64(balance)*0.99 {
bot.trySendMessage(m.Sender, Translate(ctx, "feeReserveMessage"))
@@ -112,7 +113,7 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(bolt11.Description))
}
log.Printf("[/pay] User: %s, amount: %d sat.", userStr, amount)
log.Infof("[/pay] Invoice entered. User: %s, amount: %d sat.", userStr, amount)
// object that holds all information about the send payment
id := fmt.Sprintf("pay-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
@@ -129,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),
@@ -147,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)
@@ -160,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{})
@@ -202,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 {
@@ -217,17 +214,26 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
return
}
payData.Hash = invoice.PaymentHash
payData.InTransaction = false
// do balance check for keyboard update
_, err = bot.GetUserBalance(user)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", userStr)
log.Errorln(errmsg)
}
if c.Message.Private() {
// if the command was invoked in private chat
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
// the edit below was cool, but we need to get rid of the replymarkup inline keyboard thingy for the main menu button update to work (for the new balance)
// bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
bot.tryDeleteMessage(c.Message)
bot.trySendMessage(c.Sender, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
} else {
// if the command was invoked in group chat
bot.trySendMessage(c.Sender, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePublicPaidMessage"), userStr), &tb.ReplyMarkup{})
}
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
}
@@ -236,9 +242,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
@@ -249,6 +257,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)
}
+11 -5
View File
@@ -11,7 +11,7 @@ import (
"github.com/makiuchi-d/gozxing"
"github.com/makiuchi-d/gozxing/qrcode"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
// TryRecognizeInvoiceFromQrCode will try to read an invoice string from a qr code and invoke the payment handler.
@@ -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
}
+51 -33
View File
@@ -6,14 +6,17 @@ 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"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
var (
@@ -39,9 +42,9 @@ func (bot *TipBot) SendCheckSyntax(ctx context.Context, m *tb.Message) (bool, st
}
type SendData struct {
*transaction.Base
*storage.Base
From *lnbits.User `json:"from"`
ToTelegramId int `json:"to_telegram_id"`
ToTelegramId int64 `json:"to_telegram_id"`
ToTelegramUser string `json:"to_telegram_user"`
Memo string `json:"memo"`
Message string `json:"message"`
@@ -68,11 +71,11 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
return
}
if ok, errstr := bot.SendCheckSyntax(ctx, m); !ok {
bot.trySendMessage(m.Sender, helpSendUsage(ctx, errstr))
NewMessage(m, WithDuration(0, bot))
return
}
// if ok, errstr := bot.SendCheckSyntax(ctx, m); !ok {
// bot.trySendMessage(m.Sender, helpSendUsage(ctx, errstr))
// NewMessage(m, WithDuration(0, bot))
// return
// }
// get send amount, returns 0 if no amount is given
amount, err := decodeAmountFromCommand(m.Text)
@@ -98,8 +101,14 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
}
}
// todo: this error might have been overwritten by the functions above
// we should only check for a valid amount here, instead of error and amount
// is a user given?
arg, err = getArgumentFromCommand(m.Text, 1)
if err != nil && m.Chat.Type == tb.ChatPrivate {
bot.askForUser(ctx, "", "CreateSendState", m.Text)
return
}
// is an amount given?
amount, err = decodeAmountFromCommand(m.Text)
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
bot.askForAmount(ctx, "", "CreateSendState", 0, 0, m.Text)
@@ -133,8 +142,8 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
log.Errorln(err.Error())
return
}
toUserStrMention = "@" + toUserStrWithoutAt
toUserStrWithoutAt = strings.TrimPrefix(toUserStrWithoutAt, "@")
toUserStrMention = "@" + toUserStrWithoutAt
}
err = bot.parseCmdDonHandler(ctx, m)
@@ -145,7 +154,16 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
toUserDb, err := GetUserByTelegramUsername(toUserStrWithoutAt, *bot)
if err != nil {
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), toUserStrMention))
// cut username if it's too long
if len(toUserStrMention) > 100 {
toUserStrMention = toUserStrMention[:100]
}
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), str.MarkdownEscape(toUserStrMention)))
return
}
if user.ID == toUserDb.ID {
bot.trySendMessage(m.Sender, Translate(ctx, "sendYourselfMessage"))
return
}
@@ -156,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,
@@ -198,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)
@@ -209,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{})
@@ -250,27 +263,30 @@ 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)
log.Infof("[send] Transaction sent from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
log.Infof("[💸 send] Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
// notify to user
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
// bot.trySendMessage(from.Telegram, fmt.Sprintf(Translate(ctx, "sendSentMessage"), amount, toUserStrMd))
if c.Message.Private() {
// if the command was invoked in private chat
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd), &tb.ReplyMarkup{})
// the edit below was cool, but we need to get rid of the replymarkup inline keyboard thingy for the main menu button update to work (for the new balance)
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd), &tb.ReplyMarkup{})
bot.tryDeleteMessage(c.Message)
bot.trySendMessage(c.Sender, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
} else {
// if the command was invoked in group chat
bot.trySendMessage(c.Sender, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
@@ -289,12 +305,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 {
@@ -302,6 +321,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
+291
View File
@@ -0,0 +1,291 @@
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) (shopView ShopView, err error) {
mutex.Lock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
shopView, err = bot.getUserShopview(ctx, user)
if err != nil {
return
}
deleteStatusMessages(shopView.StatusMessages, bot)
shopView.StatusMessages = make([]*tb.Message, 0)
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
mutex.Unlock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
return
}
func deleteStatusMessages(messages []*tb.Message, bot *TipBot) {
// delete all status messages from telegram
for _, msg := range messages {
bot.tryDeleteMessage(msg)
}
}
// sendStatusMessage adds a status message to the shopVoew.statusMessages
// slide and sends a status message to the user.
func (bot *TipBot) sendStatusMessage(ctx 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)
// 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)),
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)),
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
}
+7 -7
View File
@@ -13,7 +13,7 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/str"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
"gorm.io/gorm"
)
@@ -24,8 +24,8 @@ func (bot TipBot) startHandler(ctx context.Context, m *tb.Message) {
// ATTENTION: DO NOT CALL ANY HANDLER BEFORE THE WALLET IS CREATED
// WILL RESULT IN AN ENDLESS LOOP OTHERWISE
// bot.helpHandler(m)
log.Printf("[/start] User: %s (%d)\n", m.Sender.Username, m.Sender.ID)
walletCreationMsg, err := bot.Telegram.Send(m.Sender, Translate(ctx, "startSettingWalletMessage"))
log.Printf("[⭐️ /start] New user: %s (%d)\n", GetUserStr(m.Sender), m.Sender.ID)
walletCreationMsg := bot.trySendMessage(m.Sender, Translate(ctx, "startSettingWalletMessage"))
user, err := bot.initWallet(m.Sender)
if err != nil {
log.Errorln(fmt.Sprintf("[startHandler] Error with initWallet: %s", err.Error()))
@@ -80,12 +80,12 @@ func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
func (bot TipBot) createWallet(user *lnbits.User) error {
UserStr := GetUserStr(user.Telegram)
u, err := bot.Client.CreateUserWithInitialWallet(strconv.Itoa(user.Telegram.ID),
u, err := bot.Client.CreateUserWithInitialWallet(strconv.FormatInt(user.Telegram.ID, 10),
fmt.Sprintf("%d (%s)", user.Telegram.ID, UserStr),
internal.Configuration.Lnbits.AdminId,
UserStr)
if err != nil {
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err)
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err.Error())
log.Errorln(errormsg)
return err
}
@@ -94,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,
}
}
+90 -6
View File
@@ -1,19 +1,48 @@
package telegram
import (
"fmt"
"strconv"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/rate"
"github.com/eko/gocache/store"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
// getChatIdFromRecipient will parse the recipient to int64
func (bot *TipBot) getChatIdFromRecipient(to tb.Recipient) (int64, error) {
chatId, err := strconv.ParseInt(to.Recipient(), 10, 64)
if err != nil {
return 0, err
}
return chatId, nil
}
func (bot TipBot) tryForwardMessage(to tb.Recipient, what tb.Editable, options ...interface{}) (msg *tb.Message) {
msg, err := bot.Telegram.Forward(to, what, options...)
rate.CheckLimit(to)
// ChatId is used for the keyboard
chatId, err := bot.getChatIdFromRecipient(to)
if err != nil {
log.Errorf("[tryForwardMessage] error converting message recipient to int64: %v", err)
return
}
msg, err = bot.Telegram.Forward(to, what, bot.appendMainMenu(chatId, to, options)...)
if err != nil {
log.Warnln(err.Error())
}
return
}
func (bot TipBot) trySendMessage(to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
msg, err := bot.Telegram.Send(to, what, options...)
rate.CheckLimit(to)
// ChatId is used for the keyboard
chatId, err := bot.getChatIdFromRecipient(to)
if err != nil {
log.Errorf("[trySendMessage] error converting message recipient to int64: %v", err)
return
}
msg, err = bot.Telegram.Send(to, what, bot.appendMainMenu(chatId, to, options)...)
if err != nil {
log.Warnln(err.Error())
}
@@ -21,15 +50,24 @@ func (bot TipBot) trySendMessage(to tb.Recipient, what interface{}, options ...i
}
func (bot TipBot) tryReplyMessage(to *tb.Message, what interface{}, options ...interface{}) (msg *tb.Message) {
msg, err := bot.Telegram.Reply(to, what, options...)
rate.CheckLimit(to)
msg, err := bot.Telegram.Reply(to, what, bot.appendMainMenu(to.Chat.ID, to, options)...)
if err != nil {
log.Warnln(err.Error())
}
return
}
func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...interface{}) (msg *tb.Message) {
msg, err := bot.Telegram.Edit(to, what, options...)
func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...interface{}) (msg *tb.Message, err error) {
// do not attempt edit if the message did not change
sig, chat := to.MessageSig()
if chat != 0 {
sig = strconv.FormatInt(chat, 10)
}
rate.CheckLimit(sig)
_, chatId := to.MessageSig()
msg, err = bot.Telegram.Edit(to, what, bot.appendMainMenu(chatId, to, options)...)
if err != nil {
log.Warnln(err.Error())
}
@@ -37,8 +75,54 @@ func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...in
}
func (bot TipBot) tryDeleteMessage(msg tb.Editable) {
if !allowedToPerformAction(bot, msg, isAdminAndCanDelete) {
return
}
rate.CheckLimit(msg)
err := bot.Telegram.Delete(msg)
if err != nil {
log.Warnln(err.Error())
}
return
}
// allowedToPerformAction will check if bot is allowed to perform an action on the tb.Editable.
// this function will persist the admins list in cache for 5 minutes.
// if no admins list is found for this group, bot will always fetch a fresh list.
func allowedToPerformAction(bot TipBot, editable tb.Editable, action func(members []tb.ChatMember, me *tb.User) bool) bool {
switch editable.(type) {
case *tb.Message:
message := editable.(*tb.Message)
if message.Sender.ID == bot.Telegram.Me.ID {
break
}
chat := message.Chat
if chat.Type == tb.ChatSuperGroup || chat.Type == tb.ChatGroup {
admins, err := bot.Cache.Get(fmt.Sprintf("admins-%d", chat.ID))
if err != nil {
admins, err = bot.Telegram.AdminsOf(message.Chat)
if err != nil {
log.Warnln(err.Error())
return false
}
bot.Cache.Set(fmt.Sprintf("admins-%d", chat.ID), admins, &store.Options{Expiration: 5 * time.Minute})
}
if action(admins.([]tb.ChatMember), bot.Telegram.Me) {
return true
}
return false
}
}
return true
}
// isAdminAndCanDelete will check if me is in members list and allowed to delete messages
func isAdminAndCanDelete(members []tb.ChatMember, me *tb.User) bool {
for _, admin := range members {
if admin.User.ID == me.ID {
return admin.CanDeleteMessages
}
}
return false
}
+88 -6
View File
@@ -2,14 +2,17 @@ package telegram
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
tb "gopkg.in/tucnak/telebot.v2"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.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
}
@@ -21,6 +24,16 @@ func (bot TipBot) anyTextHandler(ctx context.Context, m *tb.Message) {
return
}
// check if the user clicked on the balance button
if strings.HasPrefix(m.Text, MainMenuCommandBalance) {
bot.tryDeleteMessage(m)
// overwrite the message text so it doesn't cause an infinite loop
// because balanceHandler calls anyTextHAndler...
m.Text = ""
bot.balanceHandler(ctx, m)
return
}
// could be an invoice
anyText := strings.ToLower(m.Text)
if lightning.IsInvoice(anyText) {
@@ -33,11 +46,80 @@ func (bot TipBot) anyTextHandler(ctx context.Context, m *tb.Message) {
bot.lnurlHandler(ctx, m)
return
}
if c := stateCallbackMessage[user.StateKey]; c != nil {
c(ctx, m)
//ResetUserState(user, bot)
}
}
// could be a LNURL
// var lnurlregex = regexp.MustCompile(`.*?((lnurl)([0-9]{1,}[a-z0-9]+){1})`)
if user.StateKey == lnbits.UserStateLNURLEnterAmount || user.StateKey == lnbits.UserEnterAmount {
bot.enterAmountHandler(ctx, m)
type EnterUserStateData struct {
ID string `json:"ID"` // holds the ID of the tx object in bunt db
Type string `json:"Type"` // holds type of the tx in bunt db (needed for type checking)
Amount int64 `json:"Amount"` // holds the amount entered by the user mSat
AmountMin int64 `json:"AmountMin"` // holds the minimum amount that needs to be entered mSat
AmountMax int64 `json:"AmountMax"` // holds the maximum amount that needs to be entered mSat
OiringalCommand string `json:"OiringalCommand"` // hold the originally entered command for evtl later use
}
func (bot *TipBot) askForUser(ctx context.Context, id string, eventType string, originalCommand string) (enterUserStateData *EnterUserStateData, err error) {
user := LoadUser(ctx)
if user.Wallet == nil {
return // errors.New("user has no wallet"), 0
}
enterUserStateData = &EnterUserStateData{
ID: id,
Type: eventType,
OiringalCommand: originalCommand,
}
// set LNURLPayParams in the state of the user
stateDataJson, err := json.Marshal(enterUserStateData)
if err != nil {
log.Errorln(err)
return
}
SetUserState(user, bot, lnbits.UserEnterUser, string(stateDataJson))
// Let the user enter a user and return
bot.trySendMessage(user.Telegram, Translate(ctx, "enterUserMessage"), tb.ForceReply)
return
}
// enterAmountHandler is invoked in anyTextHandler when the user needs to enter an amount
// the amount is then stored as an entry in the user's stateKey in the user database
// any other handler that relies on this, needs to load the resulting amount from the database
func (bot *TipBot) enterUserHandler(ctx context.Context, m *tb.Message) {
user := LoadUser(ctx)
if user.Wallet == nil {
return // errors.New("user has no wallet"), 0
}
if !(user.StateKey == lnbits.UserEnterUser) {
ResetUserState(user, bot)
return // errors.New("user state does not match"), 0
}
if len(m.Text) < 4 || strings.HasPrefix(m.Text, "/") {
ResetUserState(user, bot)
return
}
var EnterUserStateData EnterUserStateData
err := json.Unmarshal([]byte(user.StateData), &EnterUserStateData)
if err != nil {
log.Errorf("[EnterUserHandler] %s", err.Error())
ResetUserState(user, bot)
return
}
userstr := m.Text
// find out which type the object in bunt has waiting for an amount
// we stored this in the EnterAmountStateData before
switch EnterUserStateData.Type {
case "CreateSendState":
m.Text = fmt.Sprintf("/send %s", userstr)
bot.sendHandler(ctx, m)
return
default:
ResetUserState(user, bot)
return
}
}
+7 -13
View File
@@ -11,7 +11,7 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func helpTipUsage(ctx context.Context, errormsg string) string {
@@ -31,8 +31,6 @@ func TipCheckSyntax(ctx context.Context, m *tb.Message) (bool, string) {
}
func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
// delete the tip message after a few seconds, this is default behaviour
defer NewMessage(m, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
// check and print all commands
bot.anyTextHandler(ctx, m)
user := LoadUser(ctx)
@@ -71,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 {
@@ -112,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
}
@@ -121,15 +118,10 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
// update tooltip if necessary
messageHasTip := tipTooltipHandler(m, bot, amount, to.Initialized)
log.Infof("[tip] Transaction sent from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
log.Infof("[💸 tip] Tip from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
// notify users
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "tipSentMessage"), amount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[/tip] Error: Send message to %s: %s", toUserStr, err)
log.Errorln(errmsg)
return
}
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "tipSentMessage"), amount, toUserStrMd))
// forward tipped message to user once
if !messageHasTip {
@@ -140,5 +132,7 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
if len(tipMemo) > 0 {
bot.trySendMessage(to.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(tipMemo)))
}
// delete the tip message after a few seconds, this is default behaviour
NewMessage(m, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
return
}
+41 -46
View File
@@ -13,7 +13,7 @@ import (
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
const (
@@ -26,17 +26,22 @@ const (
type TipTooltip struct {
Message
TipAmount int `json:"tip_amount"`
ID string `json:"id"`
TipAmount int64 `json:"tip_amount"`
Ntips int `json:"ntips"`
LastTip time.Time `json:"last_tip"`
Tippers []*tb.User `json:"tippers"`
}
func (ttt TipTooltip) Key() string {
return fmt.Sprintf("tip-tool-tip:%s", ttt.ID)
}
const maxNamesInTipperMessage = 5
type TipTooltipOption func(m *TipTooltip)
func TipAmount(amount int) TipTooltipOption {
func TipAmount(amount int64) TipTooltipOption {
return func(m *TipTooltip) {
m.TipAmount = amount
}
@@ -50,6 +55,7 @@ func Tips(nTips int) TipTooltipOption {
func NewTipTooltip(m *tb.Message, opts ...TipTooltipOption) *TipTooltip {
tipTooltip := &TipTooltip{
ID: fmt.Sprintf("%d-%d", m.Chat.ID, m.ReplyTo.ID),
Message: Message{
Message: m,
},
@@ -99,8 +105,8 @@ func getTippersString(tippers []*tb.User) string {
}
// tipTooltipExists checks if this tip is already known
func tipTooltipExists(replyToId int, bot *TipBot) (bool, *TipTooltip) {
message := NewTipTooltip(&tb.Message{ReplyTo: &tb.Message{ID: replyToId}})
func tipTooltipExists(m *tb.Message, bot *TipBot) (bool, *TipTooltip) {
message := NewTipTooltip(&tb.Message{Chat: &tb.Chat{ID: m.Chat.ID}, ReplyTo: &tb.Message{ID: m.ReplyTo.ID}})
err := bot.Bunt.Get(message)
if err != nil {
return false, message
@@ -110,49 +116,48 @@ func tipTooltipExists(replyToId int, bot *TipBot) (bool, *TipTooltip) {
}
// tipTooltipHandler function to update the tooltip below a tipped message. either updates or creates initial tip tool tip
func tipTooltipHandler(m *tb.Message, bot *TipBot, amount int, initializedWallet bool) (hasTip bool) {
func tipTooltipHandler(m *tb.Message, bot *TipBot, amount int64, initializedWallet bool) (hasTip bool) {
// todo: this crashes if the tooltip message (maybe also the original tipped message) was deleted in the mean time!!! need to check for existence!
hasTip, ttt := tipTooltipExists(m.ReplyTo.ID, bot)
hasTip, ttt := tipTooltipExists(m, bot)
log.Debugf("[tip] %s has tip: %t", ttt.ID, hasTip)
if hasTip {
// update the tooltip with new tippers
err := ttt.updateTooltip(bot, m.Sender, amount, !initializedWallet)
if err != nil {
log.Println(err)
log.Errorln(err)
// could not update the message (return false to )
return false
}
} else {
tipmsg := fmt.Sprintf(tooltipTipAmountMessage, amount)
userStr := GetUserStrMd(m.Sender)
tipmsg = fmt.Sprintf(tooltipSingleTipMessage, tipmsg, userStr)
if !initializedWallet {
tipmsg = tipmsg + fmt.Sprintf("\n%s", fmt.Sprintf(tooltipChatWithBotMessage, GetUserStrMd(bot.Telegram.Me)))
}
msg, err := bot.Telegram.Reply(m.ReplyTo, tipmsg, tb.Silent)
if err != nil {
log.Errorf("[tipTooltipHandler Reply] %s", err.Error())
// todo: in case of error we should do something better than just return 0
return false
}
message := NewTipTooltip(msg, TipAmount(amount), Tips(1))
message.Tippers = appendUinqueUsersToSlice(message.Tippers, m.Sender)
runtime.IgnoreError(bot.Bunt.Set(message))
newToolTip(m, bot, amount, initializedWallet)
}
// first call will return false, every following call will return true
return hasTip
}
func newToolTip(m *tb.Message, bot *TipBot, amount int64, initializedWallet bool) {
tipmsg := fmt.Sprintf(tooltipTipAmountMessage, amount)
userStr := GetUserStrMd(m.Sender)
tipmsg = fmt.Sprintf(tooltipSingleTipMessage, tipmsg, userStr)
if !initializedWallet {
tipmsg = tipmsg + fmt.Sprintf("\n%s", fmt.Sprintf(tooltipChatWithBotMessage, GetUserStrMd(bot.Telegram.Me)))
}
msg := bot.tryReplyMessage(m.ReplyTo, tipmsg, tb.Silent)
message := NewTipTooltip(msg, TipAmount(amount), Tips(1))
message.Tippers = appendUinqueUsersToSlice(message.Tippers, m.Sender)
runtime.IgnoreError(bot.Bunt.Set(message))
log.Debugf("[newToolTip]: New reply message: %d (Bunt: %s)", msg.ID, message.Key())
}
// updateToolTip updates existing tip tool tip in Telegram
func (ttt *TipTooltip) updateTooltip(bot *TipBot, user *tb.User, amount int, notInitializedWallet bool) error {
func (ttt *TipTooltip) updateTooltip(bot *TipBot, user *tb.User, amount int64, notInitializedWallet bool) error {
ttt.TipAmount += amount
ttt.Ntips += 1
ttt.Tippers = appendUinqueUsersToSlice(ttt.Tippers, user)
ttt.LastTip = time.Now()
err := ttt.editTooltip(bot, notInitializedWallet)
if err != nil {
return err
}
ttt.editTooltip(bot, notInitializedWallet)
log.Debugf("[updateTooltip]: Update tip tooltip (Bunt: %s)", ttt.Key())
return bot.Bunt.Set(ttt)
}
@@ -161,17 +166,15 @@ func tipTooltipInitializedHandler(user *tb.User, bot TipBot) {
runtime.IgnoreError(bot.Bunt.View(func(tx *buntdb.Tx) error {
err := tx.Ascend(MessageOrderedByReplyToFrom, func(key, value string) bool {
replyToUserId := gjson.Get(value, MessageOrderedByReplyToFrom)
if replyToUserId.String() == strconv.Itoa(user.ID) {
log.Debugln("loading persistent tip tool tip messages")
if replyToUserId.String() == strconv.FormatInt(user.ID, 10) {
log.Debugln("[tipTooltipInitializedHandler] loading persistent tip tool tip messages")
ttt := &TipTooltip{}
err := json.Unmarshal([]byte(value), ttt)
if err != nil {
log.Errorln(err)
}
err = ttt.editTooltip(&bot, false)
if err != nil {
log.Errorf("[tipTooltipInitializedHandler] could not edit tooltip: %s", err.Error())
}
// edit to remove the "chat with bot" message
ttt.editTooltip(&bot, false)
}
return true
@@ -180,17 +183,9 @@ func tipTooltipInitializedHandler(user *tb.User, bot TipBot) {
}))
}
func (ttt TipTooltip) Key() string {
return fmt.Sprintf("tip-tool-tip:%s", strconv.Itoa(ttt.Message.Message.ReplyTo.ID))
}
// editTooltip updates the tooltip message with the new tip amount and tippers and edits it
func (ttt *TipTooltip) editTooltip(bot *TipBot, notInitializedWallet bool) error {
func (ttt *TipTooltip) editTooltip(bot *TipBot, notInitializedWallet bool) {
tipToolTip := ttt.getUpdatedTipTooltipMessage(GetUserStrMd(bot.Telegram.Me), notInitializedWallet)
m, err := bot.Telegram.Edit(ttt.Message.Message, tipToolTip)
if err != nil {
return err
}
ttt.Message.Message.Text = m.Text
return nil
bot.tryEditMessage(ttt.Message.Message, tipToolTip)
// ttt.Message.Message.Text = m.Text
}
+2 -2
View File
@@ -4,7 +4,7 @@ import (
"testing"
"time"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
var (
@@ -45,7 +45,7 @@ func Test_getTippersString(t *testing.T) {
func TestMessage_getTooltipMessage(t *testing.T) {
type fields struct {
Message Message
TipAmount int
TipAmount int64
Ntips int
LastTip time.Time
Tippers []*tb.User
+43 -35
View File
@@ -7,29 +7,30 @@ import (
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type Transaction struct {
ID uint `gorm:"primarykey"`
Time time.Time `json:"time"`
Bot *TipBot `gorm:"-"`
From *lnbits.User `json:"from" gorm:"-"`
To *lnbits.User `json:"to" gorm:"-"`
FromId int `json:"from_id" `
ToId int `json:"to_id" `
FromUser string `json:"from_user"`
ToUser string `json:"to_user"`
Type string `json:"type"`
Amount int `json:"amount"`
ChatID int64 `json:"chat_id"`
ChatName string `json:"chat_name"`
Memo string `json:"memo"`
Success bool `json:"success"`
FromWallet string `json:"from_wallet"`
ToWallet string `json:"to_wallet"`
FromLNbitsID string `json:"from_lnbits"`
ToLNbitsID string `json:"to_lnbits"`
ID uint `gorm:"primarykey"`
Time time.Time `json:"time"`
Bot *TipBot `gorm:"-"`
From *lnbits.User `json:"from" gorm:"-"`
To *lnbits.User `json:"to" gorm:"-"`
FromId int64 `json:"from_id" `
ToId int64 `json:"to_id" `
FromUser string `json:"from_user"`
ToUser string `json:"to_user"`
Type string `json:"type"`
Amount int64 `json:"amount"`
ChatID int64 `json:"chat_id"`
ChatName string `json:"chat_name"`
Memo string `json:"memo"`
Success bool `json:"success"`
FromWallet string `json:"from_wallet"`
ToWallet string `json:"to_wallet"`
FromLNbitsID string `json:"from_lnbits"`
ToLNbitsID string `json:"to_lnbits"`
Invoice lnbits.BitInvoice `gorm:"embedded;embeddedPrefix:invoice_"`
}
type TransactionOption func(t *Transaction)
@@ -47,7 +48,7 @@ func TransactionType(transactionType string) TransactionOption {
}
}
func NewTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int, opts ...TransactionOption) *Transaction {
func NewTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int64, opts ...TransactionOption) *Transaction {
t := &Transaction{
Bot: bot,
From: from,
@@ -69,36 +70,27 @@ func NewTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int,
}
func (t *Transaction) Send() (success bool, err error) {
// maybe remove comments, GTP-3 dreamed this up but it's nice:
// if t.From.ID == t.To.ID {
// err = fmt.Errorf("Can not send transaction to yourself.")
// return false, err
// }
// todo: remove this commend if the backend is back up
success, err = t.SendTransaction(t.Bot, t.From, t.To, t.Amount, t.Memo)
// success = true
if success {
t.Success = success
// TODO: call post-send methods
}
// save transaction to db
tx := t.Bot.logger.Save(t)
if tx.Error != nil {
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err)
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err.Error())
log.Errorln(errMsg)
}
return success, err
}
func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int, memo string) (bool, error) {
func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int64, memo string) (bool, error) {
fromUserStr := GetUserStr(from.Telegram)
toUserStr := GetUserStr(to.Telegram)
t.FromWallet = from.Wallet.ID
t.FromLNbitsID = from.ID
// check if fromUser has balance
balance, err := bot.GetUserBalance(from)
if err != nil {
@@ -124,16 +116,32 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
Memo: memo},
bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[SendTransaction] Error: Could not create invoice for user %s", toUserStr)
errmsg := fmt.Sprintf("[Send] Error: Could not create invoice for user %s", toUserStr)
log.Errorln(errmsg)
return false, err
}
t.Invoice = invoice
// pay invoice
_, err = from.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[SendTransaction] Error: Payment from %s to %s of %d sat failed", fromUserStr, toUserStr, amount)
errmsg := fmt.Sprintf("[Send] Payment failed (%s to %s of %d sat): %s", fromUserStr, toUserStr, amount, err.Error())
log.Warnf(errmsg)
return false, err
}
// check if fromUser has balance
_, err = bot.GetUserBalance(from)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
log.Errorln(errmsg)
return false, err
}
_, err = bot.GetUserBalance(to)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
log.Errorln(errmsg)
return false, err
}
return true, err
}
+8 -7
View File
@@ -3,13 +3,14 @@ package telegram
import (
"errors"
"fmt"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/eko/gocache/store"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
"gorm.io/gorm"
"time"
)
func SetUserState(user *lnbits.User, bot *TipBot, stateKey lnbits.UserStateKey, stateData string) {
@@ -59,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())
@@ -81,14 +82,14 @@ 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
bot.Cache.Set(
fmt.Sprintf("%s_balance", user.Name),
amount,
&store.Options{Expiration: 30 * time.Second},
&store.Options{Expiration: 1 * time.Hour},
)
return
}
+12 -1
View File
@@ -1,8 +1,14 @@
package main
import (
"net/http"
"runtime/debug"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/gorilla/mux"
_ "net/http/pprof"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits/webhook"
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
"github.com/LightningTipBot/LightningTipBot/internal/price"
@@ -12,7 +18,7 @@ import (
// 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 +28,11 @@ func setLogger() {
func main() {
// set logger
setLogger()
router := mux.NewRouter()
router.PathPrefix("/debug/pprof/").Handler(http.DefaultServeMux)
router.Handle("/mutex", http.HandlerFunc(mutex.ServeHTTP))
router.Handle("/mutex/unlock/{id}", http.HandlerFunc(mutex.UnlockHTTP))
go http.ListenAndServe("0.0.0.0:6060", router)
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
+14 -1
View File
@@ -40,6 +40,7 @@ sendButtonMessage = """✅ Senden"""
payButtonMessage = """✅ Bezahlen"""
payReceiveButtonMessage = """💸 Bezahlen"""
receiveButtonMessage = """✅ Empfangen"""
withdrawButtonMessage = """✅ Abheben"""
cancelButtonMessage = """🚫 Abbrechen"""
collectButtonMessage = """✅ Einsammeln"""
nextButtonMessage = """Vor"""
@@ -122,6 +123,11 @@ advancedMessage = """%s
*/faucet* 🚰 Erzeuge einen Zapfhahn: `/faucet <gesamt> <pro_user>`
*/tipjar* 🍯 Erzeuge eine Spendendose: `/tipjar <gesamt> <pro_user>`"""
# GENERIC
enterAmountRangeMessage = """⌨️ Gebe einen Betrag zwischen %d und %d sat ein."""
enterAmountMessage = """⌨️ Gebe einen Betrag ein."""
errorReasonMessage = """🚫 Fehler: %s"""
# START
startSettingWalletMessage = """🧮 Richte dein Wallet ein..."""
@@ -226,12 +232,19 @@ lnurlPaymentFailed = """🚫 Zahlung fehlgeschlagen: %s"""
lnurlInvalidAmountMessage = """🚫 Ungültiger Betrag."""
lnurlInvalidAmountRangeMessage = """🚫 Betrag muss zwischen %d und %d sat liegen."""
lnurlNoUsernameMessage = """🚫 Du musst einen Telegram Username anlegen, um per LNURL Zahlungen zu empfangen."""
lnurlEnterAmountRangeMessage = """⌨️ Gebe einen Betrag zwischen %d und %d sat ein."""
lnurlHelpText = """📖 Ups, das hat nicht geklappt. %s
*Befehl:* `/lnurl [betrag] <lnurl>`
*Beispiel:* `/lnurl LNURL1DP68GUR...`"""
# LNURL WITHDRAW
confirmLnurlWithdrawMessage = """Möchtest du diese Abhebung tätigen?\n\n💸 Betrag: %d sat"""
lnurlPreparingWithdraw = """🧮 Bereite Abhebung vor..."""
lnurlWithdrawFailed = """🚫 Abhebung gescheitert."""
lnurlWithdrawCancelled = """🚫 Abhebung abgebrochen."""
lnurlWithdrawSuccess = """✅ Abhebung angefordert."""
# LINK
walletConnectMessage = """🔗 *Verbinde dein Wallet*
+17 -3
View File
@@ -40,6 +40,7 @@ sendButtonMessage = """✅ Send"""
payButtonMessage = """✅ Pay"""
payReceiveButtonMessage = """💸 Pay"""
receiveButtonMessage = """✅ Receive"""
withdrawButtonMessage = """✅ Withdraw"""
cancelButtonMessage = """🚫 Cancel"""
collectButtonMessage = """✅ Collect"""
nextButtonMessage = """Next"""
@@ -125,6 +126,12 @@ advancedMessage = """%s
*/faucet* 🚰 Create a faucet: `/faucet <capacity> <per_user>`
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`"""
# GENERIC
enterAmountRangeMessage = """💯 Enter an amount between %d and %d sat."""
enterAmountMessage = """💯 Enter an amount."""
enterUserMessage = """👤 Enter a user."""
errorReasonMessage = """🚫 Error: %s"""
# START
startSettingWalletMessage = """🧮 Setting up your wallet..."""
@@ -229,13 +236,19 @@ lnurlPaymentFailed = """🚫 Payment failed: %s"""
lnurlInvalidAmountMessage = """🚫 Invalid amount."""
lnurlInvalidAmountRangeMessage = """🚫 Amount must be between %d and %d sat."""
lnurlNoUsernameMessage = """🚫 You need to set a Telegram username to receive payments via LNURL."""
lnurlEnterAmountRangeMessage = """⌨️ Enter an amount between %d and %d sat."""
lnurlEnterAmountMessage = """⌨️ Enter an amount."""
lnurlHelpText = """📖 Oops, that didn't work. %s
*Usage:* `/lnurl [amount] <lnurl>`
*Example:* `/lnurl LNURL1DP68GUR...`"""
# LNURL WITHDRAW
confirmLnurlWithdrawMessage = """Do you want to make this withdrawal?\n\n💸 Amount: %d sat"""
lnurlPreparingWithdraw = """🧮 Preparing withdrawal..."""
lnurlWithdrawFailed = """🚫 Withdrawal failed."""
lnurlWithdrawCancelled = """🚫 Withdrawal cancelled."""
lnurlWithdrawSuccess = """✅ Withdrawal requested."""
# LINK
walletConnectMessage = """🔗 *Link your wallet*
@@ -244,7 +257,8 @@ walletConnectMessage = """🔗 *Link your wallet*
- *BlueWallet:* Press *New wallet*, *Import wallet*, *Scan or import a file*, and scan the QR code.
- *Zeus:* Copy the URL below, press *Add a new node*, *Import* (the URL), *Save Node Config*."""
couldNotLinkMessage = """🚫 Couldn't link your wallet. Please try again later."""
couldNotLinkMessage = """🚫 Couldn't link your wallet. Please try again later."""
linkHiddenMessage = """🔍 Link hidden. Enter /link to see it again."""
# FAUCET
+40 -3
View File
@@ -17,7 +17,7 @@ linkCommandStr = """enlace"""
lnurlCommandStr = """lnurl"""
faucetCommandStr = """grifo"""
tipjarCommandStr = """bote"""
tipjarCommandStr = """alcancía"""
receiveCommandStr = """recibir"""
hideCommandStr = """ocultar"""
volcanoCommandStr = """volcán"""
@@ -122,9 +122,15 @@ advancedMessage = """%s
*/faucet* 🚰 Crear un grifo: `/faucet <capacidad> <por_usuario>`
*/tipjar* 🍯 Crear un tipjar: `/tipjar <capacidad> <por_usuario>`"""
# GENERIC
enterAmountRangeMessage = """💯 Introduce un monto entre %d y %d sat."""
enterAmountMessage = """💯 Introduce un monto."""
enterUserMessage = """👤 Introduce un usuario."""
errorReasonMessage = """🚫 Error: %s"""
# START
startSettingWalletMessage = """🧮 Configurar tu monedero..."""
startSettingWalletMessage = """🧮 Configurando tu monedero..."""
startWalletCreatedMessage = """🧮 Monedero creado."""
startWalletReadyMessage = """✅ *Tu monedero está listo.*"""
startWalletErrorMessage = """🚫 Error al iniciar tu monedero. Vuelve a intentarlo más tarde."""
@@ -226,12 +232,19 @@ lnurlPaymentFailed = """🚫 Pago fallido: %s"""
lnurlInvalidAmountMessage = """🚫 Monto inválido."""
lnurlInvalidAmountRangeMessage = """🚫 El monto debe estar entre %d y %d sat."""
lnurlNoUsernameMessage = """🚫 Tienes que establecer un nombre de usuario de Telegram para recibir pagos a través de LNURL."""
lnurlEnterAmountRangeMessage = """⌨️ Introduce un monto entre %d y %d sat."""
lnurlHelpText = """📖 Oops, eso no funcionó. %s
*Uso:* `/lnurl [monto] <lnurl>`
*Ejemplo:* `/lnurl LNURL1DP68GUR...`"""
# LNURL WITHDRAW
confirmLnurlWithdrawMessage = """¿Desea realizar este retiro?\n\n💸 Monto: %d sat"""
lnurlPreparingWithdraw = """🧮 Preparando retiro..."""
lnurlWithdrawFailed = """🚫 Retiro fallido."""
lnurlWithdrawCancelled = """🚫 Retiro cancelado."""
lnurlWithdrawSuccess = """✅ Retiro solicitado."""
# LINK
walletConnectMessage = """🔗 *Enlaza tu monedero*
@@ -297,3 +310,27 @@ inlineReceiveCreateWalletMessage = """Chatea con %s 👈 para gestionar tu carte
inlineReceiveYourselfMessage = """📖 No puedes pagarte a ti mismo."""
inlineReceiveFailedMessage = """🚫 Recepción fallida."""
inlineReceiveCancelledMessage = """🚫 Recepción cancelada."""
# TIPJAR
inlineQueryTipjarTitle = """🍯 Crear una alcancía."""
inlineQueryTipjarDescription = """Uso: @%s alcancía <capacidad> <por_usuario>"""
inlineResultTipjarTitle = """🍯 Crear una alcancía de %d sat."""
inlineResultTipjarDescription = """👉 Haz clic aquí para crear una alcancía en este chat."""
inlineTipjarMessage = """Pulsa 💸 para *pagar %d sat* a esa alcancía de %s.
🙏 Dados: *%d*/%d sat (por %d usuarios)
%s"""
inlineTipjarEndedMessage = """🍯 La alcancía de %s está llena ⭐️\n\n🏅 %d sat dados por %d usuários."""
inlineTipjarAppendMemo = """\n✉️ %s"""
inlineTipjarCancelledMessage = """🚫 Alcancía cancelada."""
inlineTipjarInvalidPeruserAmountMessage = """🚫 El monto por usuario no es divisor de la capacidad."""
inlineTipjarInvalidAmountMessage = """🚫 Monto inválido."""
inlineTipjarSentMessage = """🍯 %d sat enviado(s) a %s."""
inlineTipjarReceivedMessage = """🍯 %s te envió %d sat."""
inlineTipjarHelpTipjarInGroup = """Crea una alcancía en un grupo con el bot dentro o utiliza el 👉 comando _inline_ (/advanced para más)."""
inlineTipjarHelpText = """📖 Oops, eso no funcionó. %s
*Uso:* `/tipjar <capacidad> <por_usuario>`
*Ejemplo:* `/tipjar 210 21`"""
+6 -1
View File
@@ -122,6 +122,12 @@ advancedMessage = """%s
*/faucet* 🚰 Créer un faucet: `/faucet <capacité> <par_utilisateur>`
*/tipjar* 🍯 Créer un tipjar: `/tipjar <capacité> <par_utilisateur>`"""
# GENERIC
enterAmountRangeMessage = """💯 Choisissez un montant entre %d et %d sat."""
enterAmountMessage = """💯 Choisissez un montant."""
enterUserMessage = """👤 Choisissez un utilisateur."""
errorReasonMessage = """🚫 Erreur: %s"""
# START
startSettingWalletMessage = """🧮 Création de votre wallet..."""
@@ -226,7 +232,6 @@ lnurlPaymentFailed = """🚫 Echec du paiement : %s"""
lnurlInvalidAmountMessage = """🚫 Montant incorrect."""
lnurlInvalidAmountRangeMessage = """🚫 Le montant doit être entre %d et %d sat."""
lnurlNoUsernameMessage = """🚫 Vous devez avoir un nom d'utilisateur Telegram pour recevoir un paiement via LNURL."""
lnurlEnterAmountRangeMessage = """⌨️ Choisissez un montant entre %d et %d sat."""
lnurlHelpText = """📖 Oops, cela n'a pas fonctionné. %s
*Usage:* `/lnurl [montant] <lnurl>`
+14 -1
View File
@@ -122,6 +122,12 @@ advancedMessage = """%s
*/faucet* 🚰 Membuat sebuah keran `/faucet <kapasitas> <per_pengguna>`
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`"""
# GENERIC
enterAmountRangeMessage = """💯 Masukkan jumlah diantara %d dan %d sat."""
enterAmountMessage = """💯 Masukkan jumlah."""
enterUserMessage = """👤 Masukkan user."""
errorReasonMessage = """🚫 Error: %s"""
# START
startSettingWalletMessage = """🧮 Sedang menyiapkan dompet mu..."""
@@ -226,12 +232,19 @@ lnurlPaymentFailed = """🚫 Pembayaran gagal: %s"""
lnurlInvalidAmountMessage = """🚫 Jumlah tidak benar."""
lnurlInvalidAmountRangeMessage = """🚫 Jumlah harus diantara %d dan %d sat."""
lnurlNoUsernameMessage = """🚫 Kamu harus mengatur nama pengguna Telegram untuk menerima pembayaran melalui LNURL."""
lnurlEnterAmountRangeMessage = """⌨️ Masukkan jumlah diantara %d dan %d sat."""
lnurlHelpText = """📖 Waduh, itu tidak berhasil. %s
*Usage:* `/lnurl [jumlah] <lnurl>`
*Example:* `/lnurl LNURL1DP68GUR...`"""
# LNURL PENARIKAN
confirmLnurlWithdrawMessage = """Apakah anda ingin melakukan penarikan ini?\n\n💸 Jumlah: %d sat"""
lnurlPreparingWithdraw = """🧮 Mempersiapkan penarikan..."""
lnurlWithdrawFailed = """🚫 Penarikan gagal."""
lnurlWithdrawCancelled = """🚫 Penarikan dibatalkan."""
lnurlWithdrawSuccess = """✅ Penarikan diajukan."""
# LINK
walletConnectMessage = """🔗 *Hubungkan dompet mu*
+6 -1
View File
@@ -122,6 +122,12 @@ advancedMessage = """%s
*/faucet* 🚰 Crea una distribuzione: `/faucet <totale> <per_utente>`
*/tipjar* 🍯 Crea un tipjar: `/tipjar <totale> <per_utente>`"""
# GENERIC
enterAmountRangeMessage = """💯 Imposta un ammontare tra %d e %d sat."""
enterAmountMessage = """💯 Imposta un ammontare."""
enterUserMessage = """👤 Imposta un utente."""
errorReasonMessage = """🚫 Errore: %s"""
# START
startSettingWalletMessage = """🧮 Sto creando il tuo wallet..."""
@@ -226,7 +232,6 @@ lnurlPaymentFailed = """🚫 Pagamento non riuscito: %s"""
lnurlInvalidAmountMessage = """🚫 Ammontare non valido."""
lnurlInvalidAmountRangeMessage = """🚫 L'ammontare deve essere compreso tra %d e %d sat."""
lnurlNoUsernameMessage = """🚫 Devi impostare un nome utente Telegram per ricevere pagamenti tramite un LNURL."""
lnurlEnterAmountRangeMessage = """⌨️ Imposta un ammontare tra %d e %d sat."""
lnurlHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/lnurl [ammontare] <lnurl>`
+14 -1
View File
@@ -122,6 +122,12 @@ advancedMessage = """%s
*/faucet* 🚰 Maak een kraan: `/faucet <capacity> <per_user>`
*/tipjar* 🍯 Maak een tipjar: `/tipjar <capacity> <per_user>`"""
# GENERIC
enterAmountRangeMessage = """💯 Voer een bedrag in tussen %d en %d sat."""
enterAmountMessage = """💯 Voer een bedrag."""
enterUserMessage = """👤 Voer een gebruiker."""
errorReasonMessage = """🚫 Fout: %s"""
# START
startSettingWalletMessage = """🧮 Uw wallet instellen..."""
@@ -226,12 +232,19 @@ lnurlPaymentFailed = """🚫 Betaling mislukt: %s"""
lnurlInvalidAmountMessage = """🚫 Ongeldig bedrag."""
lnurlInvalidAmountRangeMessage = """🚫 Bedrag moet liggen tussen %d en %d sat."""
lnurlNoUsernameMessage = """🚫 U moet een Telegram gebruikersnaam instellen om betalingen te ontvangen via LNURL."""
lnurlEnterAmountRangeMessage = """⌨️ Voer een bedrag in tussen %d en %d sat."""
lnurlHelpText = """📖 Oeps, dat werkte niet. %s
*Usage:* `/lnurl [bedrag] <lnurl>`
*Example:* `/lnurl LNURL1DP68GUR...`"""
# LNURL WITHDRAW
confirmLnurlWithdrawMessage = """Wilt u deze opname maken?💸 Bedrag: %d sat"""
lnurlPreparingWithdraw = """🧮 Opname aan het voorbereiden..."""
lnurlWithdrawFailed = """🚫 Opname mislukt."""
lnurlWithdrawCancelled = """🚫 Opname geannuleerd."""
lnurlWithdrawSuccess = """✅ Opname aangevraagd."""
# LINK
walletConnectMessage = """🔗 *Koppel uw wallet*
+38 -1
View File
@@ -122,6 +122,12 @@ advancedMessage = """%s
*/faucet* 🚰 Criar uma torneira: `/faucet <capacidade> <por_usuário>`
*/tipjar* 🍯 Criar uma tipjar: `/tipjar <capacidade> <por_usuário>`"""
# GENERIC
enterAmountRangeMessage = """💯 Insira uma quantia entre %d e %d sat."""
enterAmountMessage = """💯 Insira uma quantia."""
enterUserMessage = """👤 Insira um usuário."""
errorReasonMessage = """🚫 Erro: %s"""
# START
startSettingWalletMessage = """🧮 Preparando sua carteira..."""
@@ -226,12 +232,19 @@ lnurlPaymentFailed = """🚫 Falha no pagamento: %s"""
lnurlInvalidAmountMessage = """🚫 Quantia inválida."""
lnurlInvalidAmountRangeMessage = """🚫 A quantia deve estar entre %d e %d sat."""
lnurlNoUsernameMessage = """🚫 Você precisa configurar um nome de usuário de Telegram para receber pagamentos através do LNURL."""
lnurlEnterAmountRangeMessage = """⌨️ Insira uma quantia entre %d e %d sat."""
lnurlHelpText = """📖 Opa, isso não funcionou. %s
*Uso:* `/lnurl [quantidade] <lnurl>`
*Exemplo:* `/lnurl LNURL1DP68GUR...`"""
# LNURL WITHDRAW
confirmLnurlWithdrawMessage = """Você quer fazer esse saque?\n💸 Quantia: %d sat"""
lnurlPreparingWithdraw = """🧮 Preparando o saque..."""
lnurlWithdrawFailed = """🚫 Saque falhou."""
lnurlWithdrawCancelled = """🚫 Saque cancelado."""
lnurlWithdrawSuccess = """✅ Saque solicitado."""
# LINK
walletConnectMessage = """🔗 *Vincule sua carteira*
@@ -297,3 +310,27 @@ inlineReceiveCreateWalletMessage = """Bate-papo com %s 👈 para administrar sua
inlineReceiveYourselfMessage = """📖 Você não pode pagar a si mesmo."""
inlineReceiveFailedMessage = """🚫 O recebimento falhou."""
inlineReceiveCancelledMessage = """🚫 Recepção cancelada."""
# TIPJAR
inlineQueryTipjarTitle = """🍯 Criar um cofrinho."""
inlineQueryTipjarDescription = """Uso: @%s cofrinho <capacidade> <por_usuário>"""
inlineResultTipjarTitle = """🍯 Criar um cofrinho de %d sat."""
inlineResultTipjarDescription = """👉 Clique aqui para criar um cofrinho neste chat."""
inlineTipjarMessage = """Pressione 💸 para *pagar %d sat* a esse cofrinho de %s.
🙏 Doados: *%d*/%d sat (por %d usuários)
%s"""
inlineTipjarEndedMessage = """🍯 O cofrinho de %s está cheio ⭐️\n\n🏅 %d sat doados por %d usuários."""
inlineTipjarAppendMemo = """\n✉️ %s"""
inlineTipjarCancelledMessage = """🚫 Cofrinho cancelado."""
inlineTipjarInvalidPeruserAmountMessage = """🚫 Quantidade por usuário não divisor da capacidade."""
inlineTipjarInvalidAmountMessage = """🚫 Quantia inválida."""
inlineTipjarSentMessage = """🍯 %d sat enviado(s) a %s."""
inlineTipjarReceivedMessage = """🍯 %s lhe enviou %d sat."""
inlineTipjarHelpTipjarInGroup = """Criar uma cofrinho em grupo com o bot dentro ou usar o 👉 comando_inline_ (/advanced para mais)."""
inlineTipjarHelpText = """📖 Opa, isso não funcionou. %s
*Uso:* `/tipjar <capacidade> <por_usuário>`
*Exemplo:* `/tipjar 210 21`"""
+340
View File
@@ -0,0 +1,340 @@
# COMMANDS
helpCommandStr = """справка"""
basicsCommandStr = """основы"""
tipCommandStr = """tip"""
balanceCommandStr = """баланс"""
sendCommandStr = """отправить"""
invoiceCommandStr = """инвойс"""
payCommandStr = """оплатить"""
donateCommandStr = """пожертвовать"""
advancedCommandStr = """детально"""
transactionsCommandStr = """транзакции"""
logCommandStr = """лог"""
listCommandStr = """список"""
linkCommandStr = """link"""
lnurlCommandStr = """lnurl"""
faucetCommandStr = """faucet"""
tipjarCommandStr = """tipjar"""
receiveCommandStr = """получить"""
hideCommandStr = """спрятать"""
volcanoCommandStr = """volcano"""
showCommandStr = """показать"""
optionsCommandStr = """опции"""
settingsCommandStr = """настройки"""
saveCommandStr = """сохранить"""
deleteCommandStr = """удалить"""
infoCommandStr = """инфо"""
# NOTIFICATIONS
cantDoThatMessage = """Вы не можете это сделать."""
cantClickMessage = """Вы не можете нажать на эту кнопку."""
balanceTooLowMessage = """Недостаточно средств."""
# BUTTONS
sendButtonMessage = """✅ Отправить"""
payButtonMessage = """✅ Оплатить"""
payReceiveButtonMessage = """💸 Оплатить"""
receiveButtonMessage = """✅ Получить"""
withdrawButtonMessage = """✅ Вывести"""
cancelButtonMessage = """🚫 Отмена"""
collectButtonMessage = """✅ Забрать"""
nextButtonMessage = """Вперед"""
backButtonMessage = """Назад"""
acceptButtonMessage = """Принять"""
denyButtonMessage = """Запретить"""
tipButtonMessage = """Tip"""
revealButtonMessage = """Развернуть"""
showButtonMessage = """Показать"""
hideButtonMessage = """Спрятать"""
joinButtonMessage = """Присоединиться"""
optionsButtonMessage = """Опции"""
settingsButtonMessage = """Настройки"""
saveButtonMessage = """Сохранить"""
deleteButtonMessage = """Удалить"""
infoButtonMessage = """Инфо"""
cancelButtonEmoji = """🚫"""
payButtonEmoji = """💸"""
# HELP
helpMessage = """⚡️ *Wallet*
_Этот бот представляет собой кошелек Bitcoin Lightning, который может отправлять Tip (небольшие сумму в Сатоши) через Telegram. Чтобы отправить Tip, добавьте бота в групповой чат. Основной единицей чаевых являются сатоши (sat). 100 000 000 сат = 1 биткоин. Введите 📚 /basics для получения дополнительной информации._
❤️ *Donate*
_Этот бот не взимает комиссии, но его работа обходится в сатоши. Если вам нравится бот, пожалуйста, поддержите этот проект пожертвованием. Чтобы сделать пожертвование, воспользуйтесь командой_ `/donate 1000`
%s
⚙️ *Команды*
*/tip* 🏅 Ответьте на сообщение чтобы отправить Tip (небольшую сумму в Сатоши): `/tip <amount> [<memo>]`
*/balance* 👑 Проверить баланс: `/balance`
*/send* 💸 Отправить ссредства пользователю: `/send <количество> @<user> или <user>@ln.tips [<memo>]`
*/invoice* ⚡️ Получить через Lightning: `/invoice <количество> [<memo>]`
*/pay* ⚡️ Оплатить через Lightning: `/pay <инвойс>`
*/donate* ❤️ Отправить пожертвование проекту: `/donate 1000`
*/advanced* 🤖 Продвинутые возможности.
*/help* 📖 Прочитайте справку."""
infoHelpMessage = """ℹ️ *Info*"""
infoYourLightningAddress = """Ваш адрес в системе Lightning - `%s`"""
basicsMessage = """🧡 *Биткоин*
_Биткоин - это валюта интернета. Она не имеет ограничений и децентрализована, у нее нет хозяев и контролирующих органов. Биткойн - это разумные деньги, которые быстрее, надежнее и всеохватнее, чем традиционная финансовая система._
🧮 *Экономика*
_Наименьшей единицей Биткоина являются "Сатоши" (sat), а 100 000 000 sat = 1 Биткойн. В мире существует только 21 миллион биткоинов. Стоимость Биткойна выражаемая в фиатной валюте может меняться ежедневно. Однако, если вы живете по стандарту Биткойна, то 1 sat всегда будет равен 1 sat._
⚡️ *The Lightning Network*
_The Lightning Network - это платежный протокол, который обеспечивает быстрые и дешевые платежи Биткоинами, практически не требующие энергии. Именно благодаря ему Биткоин доступен миллиардам людей по всему миру._
📲 *Lightning-кошельки*
_Ваши средства на этом боте могут быть отправлены на любой другой Lightning-кошелек и наоборот. Рекомендуемые Lightning-кошельки для вашего телефона:_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (не требующие обслуживания), или_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(простой)_.
📄 *Open Source*
_Этот бот является бесплатным и_ [с открытым исходным кодом](https://github.com/LightningTipBot/LightningTipBot) _. Вы можете запустить его на своем компьютере и использовать в своем сообществе._
✈️ *Telegram*
_Добавьте этого бота в чат вашей группы Telegram для /tip сообщений. Если вы сделаете бота администратором группы, он также будет очищать команды для поддержания чистоты в чате._
🏛 *Условия*
_Мы не являемся хранителями ваших средств. Мы будем действовать в ваших интересах, но мы также понимаем, что ситуация без поддержки стандарта KYC - немного сложная, до тех пор, пока мы не придумаем что-нибудь. Любая сумма, которую вы загрузите на свой кошелек, будет считаться пожертвованием. Не отдавайте нам все свои деньги. Имейте в виду, что этот бот находится в стадии бета-разработки. Используйте на свой страх и риск._
❤️ *Пожертвования*
_Этот бот не взимает комиссии, но его работа обходится в сатоши. Если вам нравится бот, пожалуйста, поддержите этот проект пожертвованием. Чтобы сделать пожертвование, воспользуйтесь командой_ `/donate 1000`"""
helpNoUsernameMessage = """👋 Пожалуйста, установите имя пользователя в Telegram."""
advancedMessage = """%s
👉 *Команды*
*send* 💸 Отправить Сатоши в чате: `%s send <количество> [<user>] [<memo>]`
*receive* 🏅 Запросить оплату: `... receive <количество> [<user>] [<memo>]`
*faucet* 🚰 Создать криптораздачу: `... faucet <ёмкость> <на_пользователя> [<memo>]`
*tipjar* 🍯 Создать копилку: `... tipjar <ёмкость> <на_пользователя> [<memo>]`
📖 Вы можете использовать команды в любом чате, даже в личных беседах. Подождите секунду после ввода команды и *щелкните* результат, не нажимайте Enter..
⚙️ *Продвинутые команды*
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
*/lnurl* Получить или оплатить через ⚡️Lnurl: `/lnurl` or `/lnurl <lnurl>`
*/faucet* 🚰 Создать криптораздачу: `/faucet <ёмкость> <на_пользователя>`
*/tipjar* 🍯 Создать копилку: `/tipjar <ёмкость> <на_пользователя>`"""
# GENERIC
enterAmountRangeMessage = """💯 Введите количество между %d и %d sat."""
enterAmountMessage = """💯 Введите количество."""
enterUserMessage = """👤 введите пользователя."""
errorReasonMessage = """🚫 Ошибка: %s"""
# START
startSettingWalletMessage = """🧮 Настраиваю кошелёк для вас..."""
startWalletCreatedMessage = """🧮 Кошелёк создан."""
startWalletReadyMessage = """✅ *Кошелёк готов к использованию.*"""
startWalletErrorMessage = """🚫 Ошибка инициализации кошелька. Попробуйте позже."""
startNoUsernameMessage = """☝️ Похоже, что у вас еще нет @имени_пользователя в Telegram. Это нормально, оно не обязательно для использования этого бота. Однако, чтобы лучше использовать свой кошелек, установите имя пользователя в настройках Telegram. Затем введите /balance, чтобы бот мог обновить свои данные о вас."""
# BALANCE
balanceMessage = """👑 *Ваш баланс:* %d sat"""
balanceErrorMessage = """🚫 Не удалось получить ваш баланс. Пожалуйста, повторите попытку позже."""
# TIP
tipDidYouReplyMessage = """Вы ответили на сообщение чтобы отправить Сатоши? Чтобы ответить на любое сообщение, нажмите правой кнопкой мыши -> Ответить на компьютере или проведите пальцем по сообщению на телефоне. Если вы хотите отправить Сатоши непосредственно другому пользователю, используйте команду /send."""
tipInviteGroupMessage = """ℹ️ Кстати, вы можете пригласить этого бота в любую группу, чтобы можно было отправлять чаевые там."""
tipEnterAmountMessage = """Ввели ли вы сумму?"""
tipValidAmountMessage = """Ввели ли вы правильную сумму?"""
tipYourselfMessage = """📖 Вы не можете отправлять самому себе."""
tipSentMessage = """💸 %d sat отправлено %s."""
tipReceivedMessage = """🏅 %s отправил(а) вам %d sat."""
tipErrorMessage = """🚫 Отправка не удалась."""
tipUndefinedErrorMsg = """пожалуйста попробуйте позжа."""
tipHelpText = """📖 Упс, это не сработало. %s
*Использование:* `/tip <количество> [<memo>]`
*Пример:* `/tip 1000 Спасибо!`"""
# SEND
sendValidAmountMessage = """Ввели ли вы правильную сумму?"""
sendUserHasNoWalletMessage = """🚫 Пользователь %s не создал кошелёк."""
sendSentMessage = """💸 %d sat отправлено %s."""
sendPublicSentMessage = """💸 %d sat отправил(а) %s для %s."""
sendReceivedMessage = """🏅 %s отправил(а) вам %d sat."""
sendErrorMessage = """🚫 Неуспешная отправка."""
confirmSendMessage = """Вы хотите отправить Сатоши %s?\n\n💸 Amount: %d sat"""
confirmSendAppendMemo = """\n✉️ %s"""
sendCancelledMessage = """🚫 Отправка отменена."""
errorTryLaterMessage = """🚫 Ошибка. Пожалуйста попробуйте позже."""
sendSyntaxErrorMessage = """Вы ввели сумму и получателя? Вы можете использовать команду /send для отправки либо пользователям Telegram, например %s, либо на адрес Lightning, например LightningTipBot@ln.tips."""
sendHelpText = """📖 Упс, это не сработало. %s
*Использование:* `/send <количество> <пользователь> [<memo>]`
*Пример:* `/send 1000 @LightningTipBot I just like the bot ❤️`
*Пример:* `/send 1234 LightningTipBot@ln.tips`"""
# INVOICE
invoiceReceivedMessage = """⚡️ Вы получили %d sat."""
invoiceEnterAmountMessage = """Ввели ли вы сумму?"""
invoiceValidAmountMessage = """Ввели ли вы правильную сумму?"""
invoiceHelpText = """📖 Упс, это не сработало. %s
*Использование:* `/invoice <количество> [<memo>]`
*Пример:* `/invoice 1000 Спасибо!`"""
# PAY
paymentCancelledMessage = """🚫 Платёж отменён."""
invoicePaidMessage = """⚡️ Платёж отправлен."""
invoicePublicPaidMessage = """⚡️ %s отправил(а) платёж."""
invalidInvoiceHelpMessage = """Вы ввели существующий счет в Lightning? Попробуйте /send, если вы хотите отправить пользователю Telegram или по адресу Lightning."""
invoiceNoAmountMessage = """🚫 Невозможно оплатить инвойс без указания суммы."""
insufficientFundsMessage = """🚫 Недостаточно средств. У вас есть %d sat, но вам нужно не менее %d sat."""
feeReserveMessage = """⚠️ Отправка всего вашего баланса может провалиться из-за сетевых сборов. Если это не удается, попробуйте отправить немного меньше."""
invoicePaymentFailedMessage = """🚫 Платёж не прошёл: %s"""
invoiceUndefinedErrorMessage = """Невозможно оплатить счёт."""
confirmPayInvoiceMessage = """Хотите ли вы отправить этот платеж?\n\n💸 Amount: %d sat"""
confirmPayAppendMemo = """\n✉️ %s"""
payHelpText = """📖 Упс, это не сработало. %s
*Использование:* `/pay <инвойс>`
*Пример:* `/pay lnbc20n1psscehd...`"""
# DONATE
donationSuccess = """🙏 Спасибо за ваше пожертвование."""
donationErrorMessage = """🚫 О нет! Пожертвование не удалось."""
donationProgressMessage = """🧮 Подготовка вашего пожертвования..."""
donationFailedMessage = """🚫 Пожертвование не удалось: %s"""
donateEnterAmountMessage = """Ввели ли вы сумму?"""
donateValidAmountMessage = """Ввели ли вы правильную сумму?"""
donateHelpText = """📖 Упс, это не сработало. %s
*Использование:* `/donate <количество>`
*Пример:* `/donate 1000`"""
# PHOTO
photoQrNotRecognizedMessage = """🚫 Не удалось распознать счет Lightning или LNURL. Попробуйте отцентрировать QR-код, обрезать фотографию или увеличить масштаб."""
photoQrRecognizedMessage = """✅ QR код:
`%s`"""
# LNURL
lnurlReceiveInfoText = """👇 Вы можете использовать этот статический LNURL для приема платежей."""
lnurlResolvingUrlMessage = """🧮 Уточнение адреса..."""
lnurlGettingUserMessage = """🧮 Подготовка платежа..."""
lnurlPaymentFailed = """🚫 Платеж не прошел: %s"""
lnurlInvalidAmountMessage = """🚫 Неверная сумма."""
lnurlInvalidAmountRangeMessage = """🚫 Сумма должна быть от %d до %d sat."""
lnurlNoUsernameMessage = """🚫 Вам нужно установить имя пользователя Telegram для получения платежей через LNURL."""
lnurlHelpText = """📖 Упс, это не сработало. %s
*Использование:* `/lnurl [количество] <lnurl>`
*Пример:* `/lnurl LNURL1DP68GUR...`"""
# LNURL WITHDRAW
confirmLnurlWithdrawMessage = """Вы хотите вывести средства?\n\n💸 Сумма: %d сб"""
lnurlPreparingWithdraw = """🧮 Подготовка к выводу средств..."""
lnurlWithdrawFailed = """🚫 Вывод средств не удался."""
lnurlWithdrawCancelled = """🚫 Вывод средств отменен."""
lnurlWithdrawSuccess = """✅ Вывод средств запрошен."""
# LINK
walletConnectMessage = """🔗 *Подключение кошелька*
⚠️ Никогда и никому не сообщайте URL или QR-код, иначе они смогут получить доступ к вашим средствам.
- *BlueWallet:* Нажмите *New wallet*, *Import wallet*, *Scan or import a file*, и отсканируйте QR-код.
- *Zeus:* Скопируйте URL ниже, нажмите *Add a new node*, *Import* (the URL), *Save Node Config*."""
couldNotLinkMessage = """🚫 Не удалось связать ваш кошелек. Пожалуйста, повторите попытку позже."""
# FAUCET
inlineQueryFaucetTitle = """🚰 Создать криптораздачу."""
inlineQueryFaucetDescription = """Использование: @%s faucet <capacity> <per_user>"""
inlineResultFaucetTitle = """🚰 Создать %d sat криптораздачу."""
inlineResultFaucetDescription = """👉 Нажмите здесь, чтобы создать криптораздачу в этом чате."""
inlineFaucetMessage = """Нажмите ✅, чтобы забрать %d sat из этой криптораздачи.
🚰 Осталось: %d/%d sat (отдано %d/%d пользователям)
%s"""
inlineFaucetEndedMessage = """🚰 Криптораздача завершена 🍺\n\n🏅 %d sat отдано %d пользователям."""
inlineFaucetAppendMemo = """\n✉️ %s"""
inlineFaucetCreateWalletMessage = """Напишите %s 👈 чтобы управлять своим кошельком."""
inlineFaucetCancelledMessage = """🚫 Криптораздача отменена."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Количество пользователей не является делителем емкости."""
inlineFaucetInvalidAmountMessage = """🚫 Неверное количество."""
inlineFaucetSentMessage = """🚰 %d sat отправлено %s."""
inlineFaucetReceivedMessage = """🚰 %s отправил вам %d sat."""
inlineFaucetHelpFaucetInGroup = """Создайте криптораздачу в группе с ботом внутри или используйте 👉 команду (/advanced для справки)."""
inlineFaucetHelpText = """📖 Упс, это не сработало. %s
*Использование:* `/faucet <ёмкость> <на_пользователя>`
*Пример:* `/faucet 210 21`"""
# INLINE SEND
inlineQuerySendTitle = """💸 Отправьте платеж в чат."""
inlineQuerySendDescription = """Использование: @%s send <количество> [<пользователь>] [<memo>]"""
inlineResultSendTitle = """💸 Отправить %d sat."""
inlineResultSendDescription = """👉 Нажмите, чтобы отправить %d сат в этот чат."""
inlineSendMessage = """Нажмите ✅ для получения платежа от %s.\n\n💸 Сумма: %d sat"""
inlineSendAppendMemo = """\n✉️ %s"""
inlineSendUpdateMessageAccept = """💸 %d sat отправлено с %s на %s."""
inlineSendCreateWalletMessage = """Напишите %s 👈 чтобы управлять своим кошельком."""
sendYourselfMessage = """📖 Вы не можете платить себе."""
inlineSendFailedMessage = """🚫 Отправка не удалась."""
inlineSendInvalidAmountMessage = """🚫 Сумма должна быть больше 0."""
inlineSendBalanceLowMessage = """🚫 Ваш баланс слишком низкий."""
# INLINE RECEIVE
inlineQueryReceiveTitle = """🏅 Запросить платёж в чате."""
inlineQueryReceiveDescription = """Использование: @%s receive <количество> [<пользователь>] [<memo>]"""
inlineResultReceiveTitle = """🏅 Получить %d sat."""
inlineResultReceiveDescription = """👉 Нажмите, чтобы запросить выплату в размере %d sat."""
inlineReceiveMessage = """Нажмите 💸 чтобы отправить Сатоши %s.\n\n💸 Количество: %d sat"""
inlineReceiveAppendMemo = """\n✉️ %s"""
inlineReceiveUpdateMessageAccept = """💸 %d sat отправлено от %s, получатель - %s."""
inlineReceiveCreateWalletMessage = """Напишите %s 👈 чтобы управлять своим кошельком."""
inlineReceiveYourselfMessage = """📖 Вы не можете платить себе."""
inlineReceiveFailedMessage = """🚫 Получение не удалось."""
inlineReceiveCancelledMessage = """🚫 Получение отменено."""
# TIPJAR
inlineQueryTipjarTitle = """🍯 Создать копилку."""
inlineQueryTipjarDescription = """Использование: @%s tipjar <ёмкость> <на_пользователя>"""
inlineResultTipjarTitle = """🍯 Создать копилку на %d sat ."""
inlineResultTipjarDescription = """👉 Нажмите здесь, чтобы создать копилку в этом чате."""
inlineTipjarMessage = """Нажмите 💸 чтобы *отправить %d sat* в эту копилку, созданную %s.
🙏 Накоплено: *%d*/%d sat (от %d пользователей)
%s"""
inlineTipjarEndedMessage = """🍯 %s's копилка заполнена ⭐️\n\n🏅 %d sat отправи(л/ли) %d пользовате(ль/ли)."""
inlineTipjarAppendMemo = """\n✉️ %s"""
inlineTipjarCancelledMessage = """🚫 Копилка отозвана."""
inlineTipjarInvalidPeruserAmountMessage = """🚫 Количество пользователей не является делителем емкости."""
inlineTipjarInvalidAmountMessage = """🚫 Отправка не удалась."""
inlineTipjarSentMessage = """🍯 %d sat отправлено в пользу %s."""
inlineTipjarReceivedMessage = """🍯 %s отправил вам %d sat."""
inlineTipjarHelpTipjarInGroup = """Создайте копилку в группе с ботом внутри или используйте 👉 команду (/advanced для справки)."""
inlineTipjarHelpText = """📖 Oops, that didn't work. %s
*Использование:* `/tipjar <ёмкость> <на_пользователя>`
*Пример:* `/tipjar 210 21`"""
+6 -1
View File
@@ -122,6 +122,12 @@ advancedMessage = """%s
*/faucet* 🚰 Bir fıçı oluştur: `/faucet <toplam> <kullanıcı_başına>`
*/tipjar* 🍯 Bir tipjar oluştur: `/tipjar <capacity> <per_user>`"""
# GENERIC
enterAmountRangeMessage = """💯 %d ve %d sat arasında bir miktar gir."""
enterAmountMessage = """💯 Bir miktar gir."""
enterUserMessage = """👤 Bir kullanıcı gir."""
errorReasonMessage = """🚫 Hata: %s"""
# START
startSettingWalletMessage = """🧮 Cüzdanın hazırlanıyor…"""
@@ -226,7 +232,6 @@ lnurlPaymentFailed = """🚫 Ödeme başarısız: %s"""
lnurlInvalidAmountMessage = """🚫 Geçersiz miktar."""
lnurlInvalidAmountRangeMessage = """🚫 Miktar %d ve %d sat arasında olmalı."""
lnurlNoUsernameMessage = """🚫 LNURL ödemesi almak için bir Telegram kullanıcı ismi seçmelisin."""
lnurlEnterAmountRangeMessage = """⌨️ %d ve %d sat arasında bir miktar gir."""
lnurlHelpText = """📖 Hoppalaa… olmadı. %s
*Komut:* `/lnurl [miktar] <lnurl>`