Compare commits

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

* yolo master

* logging

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

* yolo master

* add once + singleton click interceptor

* yoooo;

* stuff

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

* yolo master

* finish the faucet when inactive

* delete comments

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

* yolo master

* fix it

* decrease limit

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

* yolo master

* fix it

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

* yolo master

* coool

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

* yolo master

* rate limit

* decrease

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

* yolo master

* rate limit

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

* fix keyboard

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

* yolo master

* faucet cancel not

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

* yolo master

* faucet fix

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

* yolo master

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

* cancel better

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

* yp

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

* base canceled flag

* oops

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

* cancel

* check better

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

* cancel

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

* faucet logging

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

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

* better logging and lnurl lightning: prefix

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

* better logging

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

* reduce min faucet

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

* add pprof

* fix mutex lock

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

* tip fix lock

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

* use answerCallbackInterceptor

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

* remove panic

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

* Update mutex.go

* sync mutex

* mutex bracket

* add idInterceptor

* context lock

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

* fix pointer

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

* Update mutex.go

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

* add bunt cache

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

* faucet set after validation

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

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

* transaction to storage

* to base

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

* remove log

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

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

* fix get

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

* handling

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

* tiptooltip better

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

* add shops

* shop

* scrolling

* 🚀 add state stateCallbackMessage 🚀

* no shop

* scroll

* add shop browser

* scroll bug

* add buttons.go

* scrolling

* shop

* lnurl print after serving

* shop deletion

* adding and removing shops

* display photo captions

* refactor

* shops

* shops

* files work

* rename shop

* error handling

* fixes

* payments

* confirm delete all shops

* adding new items fix

* own bunt db for shop

* unlock transaction

* remove double print

* add transaction.Lock(id)

* unlock getShop

* add default interceptors to shop

* more files

* go sleep

* add fileStateResetTicker

* async sleep

* add runtime.ResettableFunctionTicker

* remove default duration

* generalized concurrent mutex

* simplify function ticker

* status message ticker queue

* add start index to shopViewDeleteAllStatusMsgs

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

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

* log trace level

* get rid of default interceptors

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

* add logging

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

* log trace level

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

* webhook fix

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

* remove tx timeout errors

* cacel faucet on error

* cancle faucet on error

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

* remove tx timeout errors

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

* clean up

* refactor lnurl comment notification

* fix function name

* transaction: do not check balance; refactor invoice notifications

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

* debug for tip

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

* check balance

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

* receive via invoice

* update telebot to save message InlineID

* remove debug ifs

* correct response

* comment

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

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

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

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

* dunno

* fix after interceptor

* getTelegramUserFromInterface

* clean up requireUserInterceptor

* clean up bs

* cleanup

* cleanup2

* add comment

* fix before default interceptor

* async sleep

* back to 60

* remove newline

* adding defer interceptor

* handlers tighter

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

* remove isAdminAndCanEdit on tryEdit

* remove isAdminAndCanEdit
2021-12-07 10:34:37 +01:00
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
LightningTipBotandGitHub 11edce049e General amount (#118)
* generalized amount started

* add new file

* uncomment old pay

* longer comments

* lnurl pay with generalized amount input

* generalized amount for /invoice

* amount input for all commands

* remove logging

* delete old comments
2021-10-30 21:26:01 +02:00
e4833bd9c6 User cache (#117)
* adding users cache in memory

* adding users cache in memory

* adding eko/gocache and removing CopyLowercaseUser

* using UpdateUserRecord

* updateCachedUser in user states

* remove redundant updatePersistentUser

* refactor

* remove cachedUser

* remove user chan

* errors for failed invoice creation

* errors for failed invoice and failed pay

* add GetUserBalanceCached inline commands

* translation

* remove redundant set user state reset state

* update cache ttl

Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-10-29 22:04:53 +02:00
LightningTipBotandGitHub 51c410c045 Tipjar hotfix2: translations and help (#116)
* translations and help

* shorten it
2021-10-27 15:23:01 +02:00
LightningTipBotandGitHub f0385128db add username to tipjar (#115) 2021-10-27 12:04:32 +02:00
LightningTipBotandGitHub c90cfd9d8a tipjar (#114)
* tipjar

* tipjar

* fix pointers and wallet keys

* better comment
2021-10-27 11:55:59 +02:00
LightningTipBotandGitHub 97b6e8f043 LNURL errors verbose (#110)
* internal/telegram/lnurl.go

* update gjson
2021-10-26 19:37:04 +02:00
LightningTipBotandGitHub 8da9e0c38c atoi is 32 bit only, change to ParseInt (#109) 2021-10-24 20:52:24 +02:00
fd9ad39b0c anonymous user ID for lnurl (#107)
* anonymous user ID for lnurl

* anonymous lnurl

* migrate at every start, not good

* anon id at user creation

* migrations file

* fix database migration task

* remove comment

* anon label

Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-10-24 20:31:52 +02:00
bb00253122 Translation Indonesian (#106)
* Translation to Indonesian language

First time using github but I think I did everything correctly though.
Truly sorry if I've made a noob mistake
Trying to make the language as friendly yet polite and as formal as possible
Thanx and keep up the great work

* inline commands in english

* readd en.toml

* enable translation

Co-authored-by: hmalau <92701132+hmalau@users.noreply.github.com>
2021-10-18 20:46:59 +02:00
LightningTipBotandGitHub 10c9121cc7 lnurl for user id (#104)
* lnurl for user id

* adjust help
2021-10-18 10:30:07 +02:00
LightningTipBotandGitHub 236097a461 inline send and receive to specific user (#103) 2021-10-17 16:13:41 +02:00
LightningTipBotandGitHub 22d4ab284c turkish translations (#101)
* turkish translations

* fix

* fix

* fix

* add tr.toml
2021-10-13 17:13:28 +03:00
71 changed files with 7500 additions and 1422 deletions
+1
View File
@@ -13,4 +13,5 @@ invoice - Receive with Lightning: /invoice 1000
pay - Pay with Lightning: /pay lnbc10n1ps...
donate - Donate: /donate 1000
faucet - Create a faucet: /faucet 2100 21
tipjar - Create a tipjar: /tipjar 100 10
advanced - Advanced help
+12 -7
View File
@@ -4,21 +4,26 @@ go 1.15
require (
github.com/BurntSushi/toml v0.3.1
github.com/fiatjaf/go-lnurl v1.4.0
github.com/eko/gocache v1.2.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/sirupsen/logrus v1.2.0
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/btree v0.6.1 // indirect
github.com/tidwall/buntdb v1.2.6
github.com/tidwall/gjson v1.8.1
github.com/tidwall/pretty v1.2.0 // indirect
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
+475 -17
View File
@@ -1,19 +1,49 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
git.schwanenlied.me/yawning/bsaes.git v0.0.0-20180720073208-c0276d75487e/go.mod h1:BWqTsj8PgcPriQJGl7el20J/7TuT1d/hSyFDXMEpoEo=
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ=
github.com/NebulousLabs/fastrand v0.0.0-20181203155948-6fb6489aac4e/go.mod h1:Bdzq+51GR4/0DIhaICZEOm+OHvXGwwB2trKZ8B4Y6eQ=
github.com/NebulousLabs/go-upnp v0.0.0-20180202185039-29b680b06c82/go.mod h1:GbuBk21JqF+driLX3XtJYNZjGa45YDoa9IqCTzNSfEc=
github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo=
github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI=
github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g=
github.com/XiaoMi/pegasus-go-client v0.0.0-20210427083443-f3b6b08bc4c2 h1:pami0oPhVosjOu/qRHepRmdjD6hGILF7DBr+qQZeP10=
github.com/XiaoMi/pegasus-go-client v0.0.0-20210427083443-f3b6b08bc4c2/go.mod h1:jNIx5ykW1MroBuaTja9+VpglmaJOUzezumfhLlER3oY=
github.com/Yawning/aez v0.0.0-20180114000226-4dad034d9db2/go.mod h1:9pIqrY6SXNL8vjRQE5Hd/OL5GyK/9MrGUWs87z/eFfk=
github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da/go.mod h1:eHEWzANqSiWQsof+nXEI9bUVUyV6F53Fp89EuCh2EAA=
github.com/aead/siphash v1.0.1 h1:FwHfE/T45KPKYuuSAKyyvE+oPWcaQ+CUmFW0bPlM+kg=
github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII=
github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
github.com/allegro/bigcache/v2 v2.2.5 h1:mRc8r6GQjuJsmSKQNPsR5jQVXc8IJ1xsW5YXUYMLfqI=
github.com/allegro/bigcache/v2 v2.2.5/go.mod h1:FppZsIO+IZk7gCuj5FiIDHGygD9xvWQcqg1uIPMb6tY=
github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ=
github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ=
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/aryann/difflib v0.0.0-20170710044230-e206f873d14a/go.mod h1:DAHtR1m6lCRdSC2Tm3DSWRPvIPr6xNKyeHdqDQSQT+A=
github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY=
github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQwij/eHl5CU=
github.com/aws/aws-sdk-go v1.27.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b h1:L/QXpzIa3pOvUGt1D1lA5KjYhPBAN/3iWdP7xeFS9F0=
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA=
github.com/btcsuite/btcd v0.0.0-20190629003639-c26ffa870fd8/go.mod h1:3J08xEfcugPacsc34/LKRU2yO7YmuT8yt28J8k2+rrI=
github.com/btcsuite/btcd v0.0.0-20190824003749-130ea5bddde3/go.mod h1:3J08xEfcugPacsc34/LKRU2yO7YmuT8yt28J8k2+rrI=
github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ=
@@ -54,50 +84,177 @@ github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792 h1:R8vQdOQdZ9Y3SkEwmHoWBmX1DNXhXZqlTpq6s4tyJGc=
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY=
github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs=
github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ=
github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4=
github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM=
github.com/cenkalti/backoff/v4 v4.1.0 h1:c8LkOFQTzuO0WBM/ae5HdGQuZPfPxp7lqBRwQRm4fSc=
github.com/cenkalti/backoff/v4 v4.1.0/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY=
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/clbanning/x2j v0.0.0-20191024224557-825249438eec/go.mod h1:jMjuTZXRI4dUb/I5gc9Hdhagfvm9+RyrPryS/auMzxE=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8=
github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI=
github.com/coocood/freecache v1.1.1 h1:uukNF7QKCZEdZ9gAV7WQzvh0SbjwdMF6m3x3rxEkaPc=
github.com/coocood/freecache v1.1.1/go.mod h1:OKrEjkGVoxZhyWAJoeFi5BMLUJm2Tit0kpGkIr7NGYY=
github.com/coreos/bbolt v1.3.3 h1:n6AiVyVRKQFNb6mJlwESEvvLoDyiTzXX7ORAUlkeBdY=
github.com/coreos/bbolt v1.3.3/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
github.com/davecgh/go-spew v0.0.0-20151105211317-5215b55f46b2/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgraph-io/ristretto v0.0.3 h1:jh22xisGBjrEVnRZ1DVTpBVQm0Xndu8sMl0CWDzSIBI=
github.com/dgraph-io/ristretto v0.0.3/go.mod h1:KPxhHT9ZxKefz+PCeOGsrHpl1qZ7i70dGTu2u+Ahh6E=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA=
github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZgvJUkLughtfhJv5dyTYa91l1fOUCrgjqmcifM=
github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs=
github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU=
github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I=
github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M=
github.com/eko/gocache v1.2.0 h1:SCtTs65qMXjhdtu62yHPCQuzdMkQjP+fQmkNrVutkRw=
github.com/eko/gocache v1.2.0/go.mod h1:6u8/2bnr+nOf87mRXWS710rqNNZUECF4CGsPNnsoJ78=
github.com/elazarl/goproxy v0.0.0-20170405201442-c4fc26588b6e/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc=
github.com/emicklei/go-restful v0.0.0-20170410110728-ff4f55a20633/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs=
github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4safvEdbitLhGGK48rN6g=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/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=
github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g=
github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4=
github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20=
github.com/frankban/quicktest v1.2.2/go.mod h1:Qh/WofXFeiAFII1aEBu529AtJo6Zg2VHscnEsbBnJ20=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-errors/errors v1.0.1 h1:LUHzmkK3GUKUrL/1gfBUxAHzcev3apQlezX/+O7ma6w=
github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-kit/kit v0.10.0/go.mod h1:xUsJbQ/Fp4kEt7AFgCuvyX4a71u8h9jB8tj/ORgOZ7o=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas=
github.com/go-openapi/errors v0.19.2/go.mod h1:qX0BLWsyaKfvhluLejVpVNwNRdXZhEbTA4kxxpKBC94=
github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0=
github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1:W3Z9FmVs9qj+KR4zFKmDPGiLdk1D9Rlm7cyMvf57TTg=
github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc=
github.com/go-openapi/strfmt v0.19.5/go.mod h1:eftuHTlB/dI8Uq8JJOyRlieZf+WkkxUuk0dgdHXr2Qk=
github.com/go-openapi/swag v0.0.0-20160704191624-1d0bd113de87/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I=
github.com/go-redis/redis/v8 v8.8.2 h1:O/NcHqobw7SEptA0yA6up6spZVFtwE06SXM8rgLtsP8=
github.com/go-redis/redis/v8 v8.8.2/go.mod h1:F7resOH5Kdug49Otu24RjHWwgK7u9AmtqWMnCV1iP5Y=
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/gogo/googleapis v1.1.0/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
github.com/gogo/protobuf v1.2.2-0.20190723190241-65acae22fc9d/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.5.0 h1:jlYHihg//f7RRwuPfptm04yp4s7O6Kw8EZiVYIGcH0g=
github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8=
github.com/golang/protobuf v0.0.0-20161109072736-4bd1920723d7/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.4.3 h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM=
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.2.1-0.20190312032427-6f77996f0c42/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v0.0.0-20161122191042-44d81051d367/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
github.com/grpc-ecosystem/grpc-gateway v1.8.6/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
github.com/hashicorp/consul/api v1.3.0/go.mod h1:MmDNSzIMUjNpY/mQ398R4bk2FnqQLoPndWW5VkKPlCE=
github.com/hashicorp/consul/sdk v0.3.0/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=
github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU=
github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU=
github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4=
github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=
github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=
github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I=
github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc=
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg=
github.com/imroc/req v0.3.0 h1:3EioagmlSG+z+KySToa+Ylo3pTFZs+jh3Brl7ngU12U=
github.com/imroc/req v0.3.0/go.mod h1:F+NZ+2EFSo6EFXdeIbpfE9hcC233id70kf0byW97Caw=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo=
github.com/jackpal/gateway v1.0.5/go.mod h1:lTpwd4ACLXmpyiCTRtfiNyVnUmqT9RivzCDQetPfnjA=
github.com/jackpal/go-nat-pmp v0.0.0-20170405195558-28a68d0c24ad/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc=
github.com/jedib0t/go-pretty v4.3.0+incompatible/go.mod h1:XemHduiw8R651AF9Pt4FwCTKeG3oo7hrHJAoznj9nag=
@@ -110,8 +267,18 @@ github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkr
github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jinzhu/now v1.1.2 h1:eVKgfIdy9b6zbWBMgFpfDPoAMifwSZagU9HmEU6zgiI=
github.com/jinzhu/now v1.1.2/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4=
github.com/jrick/logrotate v1.0.0 h1:lQ1bL/n9mBNeIXoTUoYRlK4dHuNJVofX9oWqBtPnSzI=
github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ=
github.com/json-iterator/go v0.0.0-20180612202835-f2b4162afba3/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.8/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/juju/clock v0.0.0-20190205081909-9c5c9712527c/go.mod h1:nD0vlnrUjcjJhqN5WuCWZyzfd5AHZAC9/ajvbSx69xA=
github.com/juju/errors v0.0.0-20190806202954-0232dcc7464d/go.mod h1:W54LbzXuIE0boCoNJfwqpmkKJ1O4TCTZMetAt6jGk7Q=
github.com/juju/loggo v0.0.0-20190526231331-6e530bcce5d8/go.mod h1:vgyd7OREkbtVEN/8IXZe5Ooef3LQePvuBm9UWj6ZL8U=
@@ -120,12 +287,17 @@ github.com/juju/testing v0.0.0-20190723135506-ce30eb24acd2/go.mod h1:63prj8cnj0t
github.com/juju/utils v0.0.0-20180820210520-bf9cc5bdd62d/go.mod h1:6/KLg8Wz/y2KVGWEpkK9vMNGkOnu4k/cqs8Z1fKjTOk=
github.com/juju/version v0.0.0-20180108022336-b64dbd566305/go.mod h1:kE8gK5X0CImdr7qpSKl3xB2PmpySSmfj7zVbkZFs81U=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4=
github.com/kkdai/bstream v0.0.0-20181106074824-b3251f7901ec h1:n1NeQ3SgUHyISrjFFoO5dR748Is8dBL9qpaTNfphQrs=
github.com/kkdai/bstream v0.0.0-20181106074824-b3251f7901ec/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4=
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
@@ -147,169 +319,444 @@ github.com/lightningnetwork/lnd/queue v1.0.3 h1:5ufYVE7lh9GJnL1wOoeO3bZ3aAHWNnkN
github.com/lightningnetwork/lnd/queue v1.0.3/go.mod h1:YTkTVZCxz8tAYreH27EO3s8572ODumWrNdYW2E/YKxg=
github.com/lightningnetwork/lnd/ticker v1.0.0 h1:S1b60TEGoTtCe2A0yeB+ecoj/kkS4qpwh6l+AkQEZwU=
github.com/lightningnetwork/lnd/ticker v1.0.0/go.mod h1:iaLXJiVgI1sPANIF2qYYUJXjoksPNvGNYowB8aRbpX0=
github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM=
github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4=
github.com/ltcsuite/ltcd v0.0.0-20190101042124-f37f8bf35796 h1:sjOGyegMIhvgfq5oaue6Td+hxZuf3tDC8lAPrFldqFw=
github.com/ltcsuite/ltcd v0.0.0-20190101042124-f37f8bf35796/go.mod h1:3p7ZTf9V1sNPI5H8P3NkTFF4LuwMdPl2DodF60qAKqY=
github.com/ltcsuite/ltcutil v0.0.0-20181217130922-17f3b04680b6/go.mod h1:8Vg/LTOO0KYa/vlHWJ6XZAevPQThGH5sufO0Hrou/lA=
github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ=
github.com/mailru/easyjson v0.0.0-20160728113105-d5b7844b561a/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/makiuchi-d/gozxing v0.0.2 h1:TGSCQRXd9QL1ze1G1JE9sZBMEr6/HLx7m5ADlLUgq7E=
github.com/makiuchi-d/gozxing v0.0.2/go.mod h1:Tt5nF+kNliU+5MDxqPpsFrtsWNdABQho/xdCZZVKCQc=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-sqlite3 v1.14.5 h1:1IdxlwTNazvbKJQSxoJ5/9ECbEeaTTyeU7sEAZ5KKTQ=
github.com/mattn/go-sqlite3 v1.14.5/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/miekg/dns v0.0.0-20171125082028-79bfde677fa8 h1:PRMAcldsl4mXKJeRNB/KVNz6TlbS6hk2Rs42PqgU3Ws=
github.com/miekg/dns v0.0.0-20171125082028-79bfde677fa8/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/miekg/dns v1.0.14 h1:9jZdLNd/P4+SfEJ0TNyxYpsK8N4GtfylBLqtbYN1sbA=
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI=
github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg=
github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY=
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180320133207-05fbef0ca5da/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/nicksnyder/go-i18n v1.10.1 h1:isfg77E/aCD7+0lD/D00ebR2MV5vgeQ276WYyDaCRQc=
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw=
github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg=
github.com/nats-io/jwt v0.3.2/go.mod h1:/euKqTS1ZD+zzjYrY7pseZrTtWQSjujC7xjPc8wL6eU=
github.com/nats-io/nats-server/v2 v2.1.2/go.mod h1:Afk+wRZqkMQs/p45uXdrVLuab3gwv3Z8C4HTBu8GD/k=
github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w=
github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
github.com/nicksnyder/go-i18n/v2 v2.1.2 h1:QHYxcUJnGHBaq7XbvgunmZ2Pn0focXFqTD61CkH146c=
github.com/nicksnyder/go-i18n/v2 v2.1.2/go.mod h1:d++QJC9ZVf7pa48qrsRWhMJ5pSHIPmS3OLqK1niyLxs=
github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/oklog/oklog v0.3.2/go.mod h1:FCV+B7mhrz4o+ueLpx+KqkyXRGMWOYEvfiXtdGtbWGs=
github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo=
github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs=
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
github.com/onsi/ginkgo v1.15.0 h1:1V1NfVQR87RtWAgp1lv9JZJ5Jap+XFGKPi00andXGi4=
github.com/onsi/ginkgo v1.15.0/go.mod h1:hF8qUzuuC8DJGygJH3726JnCZX4MYbRB8yFfISqnKUg=
github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA=
github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA=
github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU=
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.10.5 h1:7n6FEkpFmfCoo2t+YYqXH0evK+a9ICQz0xcAy9dYcaQ=
github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48=
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk=
github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492/go.mod h1:Ngi6UdF0k5OKD5t5wlmGhe/EDKPoUM3BXZSSfIuJbis=
github.com/opentracing/basictracer-go v1.0.0/go.mod h1:QfBfYuafItcjQuMwinw9GhYKwFXS9KnPs5lxoYwgW74=
github.com/opentracing/opentracing-go v1.0.2/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxSfWAKL3wpBW7V8scJMt8N8gnaMCS9E/cA=
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=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k=
github.com/pegasus-kv/thrift v0.13.0 h1:4ESwaNoHImfbHa9RUGJiJZ4hrxorihZHk5aarYwY8d4=
github.com/pegasus-kv/thrift v0.13.0/go.mod h1:Gl9NT/WHG6ABm6NsrbfE8LiJN0sAyneCrvB4qN4NPqQ=
github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac=
github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc=
github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA=
github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs=
github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og=
github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M=
github.com/prometheus/client_golang v1.10.0/go.mod h1:WJM3cc3yu7XKBKa/I8WeZm+V3eltZnBwfENSU7mdogU=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/client_model v0.1.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA=
github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo=
github.com/prometheus/common v0.18.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16Clt/msog/s=
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A=
github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E=
github.com/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=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72 h1:qLC7fQah7D6K1B0ujays3HV9gkFtllcxhzImRR7ArPQ=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=
github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=
github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/testify v0.0.0-20151208002404-e3a8ff8ce365/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/tidwall/btree v0.6.0 h1:JLYAFGV+1gjyFi3iQbO/fupBin+Ooh7dxqVV0twJ1Bo=
github.com/tidwall/btree v0.6.0/go.mod h1:TzIRzen6yHbibdSfK6t8QimqbUnoxUSrZfeW7Uob0q4=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/tidwall/assert v0.1.0 h1:aWcKyRBUAdLoVebxo95N7+YZVTFF/ASTr7BN4sLP6XI=
github.com/tidwall/assert v0.1.0/go.mod h1:QLYtGyeqse53vuELQheYl9dngGCJQ+mTtlxcktb+Kj8=
github.com/tidwall/btree v0.6.1 h1:75VVgBeviiDO+3g4U+7+BaNBNhNINxB0ULPT3fs9pMY=
github.com/tidwall/btree v0.6.1/go.mod h1:TzIRzen6yHbibdSfK6t8QimqbUnoxUSrZfeW7Uob0q4=
github.com/tidwall/buntdb v1.2.6 h1:eS0QSmzHfCKjxxYGh8eH6wnK5VLsJ7UjyyIr29JmnEg=
github.com/tidwall/buntdb v1.2.6/go.mod h1:zpXqlA5D2772I4cTqV3ifr2AZihDgi8FV7xAQu6edfc=
github.com/tidwall/buntdb v1.2.7 h1:SIyObKAymzLyGhDeIhVk2Yc1/EwfCC75Uyu77CHlVoA=
github.com/tidwall/buntdb v1.2.7/go.mod h1:b6KvZM27x/8JLI5hgRhRu60pa3q0Tz9c50TyD46OHUM=
github.com/tidwall/gjson v1.6.0/go.mod h1:P256ACg0Mn+j1RXIDXoss50DeIABTYK1PULOJHhxOls=
github.com/tidwall/gjson v1.6.1 h1:LRbvNuNuvAiISWg6gxLEFuCe72UKy5hDqhxW/8183ws=
github.com/tidwall/gjson v1.6.1/go.mod h1:BaHyNc5bjzYkPqgLq7mdVzeiRtULKULXLgZFKsxEHI0=
github.com/tidwall/gjson v1.8.0 h1:Qt+orfosKn0rbNTZqHYDqBrmm3UDA4KRkv70fDzG+PQ=
github.com/tidwall/gjson v1.8.0/go.mod h1:5/xDoumyyDNerp2U36lyolv46b3uF/9Bu6OfyQ9GImk=
github.com/tidwall/gjson v1.8.1 h1:8j5EE9Hrh3l9Od1OIEDAb7IpezNA20UdRngNAj5N0WU=
github.com/tidwall/gjson v1.8.1/go.mod h1:5/xDoumyyDNerp2U36lyolv46b3uF/9Bu6OfyQ9GImk=
github.com/tidwall/grect v0.1.2 h1:wKVeQVZhjaFCKTTlpkDe3Ex4ko3cMGW3MRKawRe8uQ4=
github.com/tidwall/grect v0.1.2/go.mod h1:v+n4ewstPGduVJebcp5Eh2WXBJBumNzyhK8GZt4gHNw=
github.com/tidwall/gjson v1.10.2 h1:APbLGOM0rrEkd8WBw9C24nllro4ajFuJu0Sc9hRz8Bo=
github.com/tidwall/gjson v1.10.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/grect v0.1.3 h1:z9YwQAMUxVSBde3b7Sl8Da37rffgNfZ6Fq6h9t6KdXE=
github.com/tidwall/grect v0.1.3/go.mod h1:8GMjwh3gPZVpLBI/jDz9uslCe0dpxRpWDdtN0lWAS/E=
github.com/tidwall/lotsa v1.0.2 h1:dNVBH5MErdaQ/xd9s769R31/n2dXavsQ0Yf4TMEHHw8=
github.com/tidwall/lotsa v1.0.2/go.mod h1:X6NiU+4yHA3fE3Puvpnn1XMDrFZrE9JO2/w+UMuqgR8=
github.com/tidwall/match v1.0.1 h1:PnKP62LPNxHKTwvHHZZzdOAOCtsJTjo6dZLCwpKm5xc=
github.com/tidwall/match v1.0.1/go.mod h1:LujAq0jyVjBy028G1WhWfIzbpQfMO8bBZ6Tyb0+pL9E=
github.com/tidwall/match v1.0.3 h1:FQUVvBImDutD8wJLN6c5eMzWtjgONK9MwIBCOrUJKeE=
github.com/tidwall/match v1.0.3/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/tidwall/pretty v1.0.2 h1:Z7S3cePv9Jwm1KwS0513MRaoUe3S01WPbLNV40pwWZU=
github.com/tidwall/pretty v1.0.2/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/tidwall/pretty v1.1.0 h1:K3hMW5epkdAVwibsQEfR/7Zj0Qgt4DxtNumTq/VloO8=
github.com/tidwall/pretty v1.1.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/rtred v0.1.2 h1:exmoQtOLvDoO8ud++6LwVsAMTu0KPzLTUrMln8u1yu8=
github.com/tidwall/rtred v0.1.2/go.mod h1:hd69WNXQ5RP9vHd7dqekAz+RIdtfBogmglkZSRxCHFQ=
github.com/tidwall/tinyqueue v0.1.1 h1:SpNEvEggbpyN5DIReaJ2/1ndroY8iyEGxPYxoSaymYE=
github.com/tidwall/tinyqueue v0.1.1/go.mod h1:O/QNHwrnjqr6IHItYrzoHAKYhBkLI67Q096fQP5zMYw=
github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/tv42/zbase32 v0.0.0-20160707012821-501572607d02/go.mod h1:tHlrkM198S068ZqfrO6S8HsoJq2bF3ETfTL+kt4tInY=
github.com/urfave/cli v1.18.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
go.etcd.io/bbolt v1.3.3 h1:MUGmc65QhB3pIlaQ5bB4LwqSj6GIonVJXpZiaKNyaKk=
go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg=
go.mongodb.org/mongo-driver v1.0.3/go.mod h1:u7ryQJ+DOzQmeO7zB6MHyr8jkEQvC8vH7qLUO4lqsUM=
go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk=
go.opencensus.io v0.20.2/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk=
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opentelemetry.io/otel v0.19.0 h1:Lenfy7QHRXPZVsw/12CWpxX6d/JkrX8wrx2vO8G80Ng=
go.opentelemetry.io/otel v0.19.0/go.mod h1:j9bF567N9EfomkSidSfmMwIwIBuP37AMAIzVW85OxSg=
go.opentelemetry.io/otel/metric v0.19.0 h1:dtZ1Ju44gkJkYvo+3qGqVXmf88tc+a42edOywypengg=
go.opentelemetry.io/otel/metric v0.19.0/go.mod h1:8f9fglJPRnXuskQmKpnad31lcLJ2VmNNqIsx/uIwBSc=
go.opentelemetry.io/otel/oteltest v0.19.0 h1:YVfA0ByROYqTwOxqHVZYZExzEpfZor+MU1rU+ip2v9Q=
go.opentelemetry.io/otel/oteltest v0.19.0/go.mod h1:tI4yxwh8U21v7JD6R3BcA/2+RBoTKFexE/PJ/nSO7IA=
go.opentelemetry.io/otel/trace v0.19.0 h1:1ucYlenXIDA1OlHVLDZKX0ObXV5RLaq06DtUKz5e5zc=
go.opentelemetry.io/otel/trace v0.19.0/go.mod h1:4IXiNextNOpPnRlI4ryK69mn5iC84bjBWZQA5DXz/qg=
go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4=
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA=
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM=
golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190211182817-74369b46fc67/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 h1:cg5LA/zNPRzIXIWSCxQW10Rvpy94aQh3LT/ShoCpkHw=
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20170114055629-f2499483f923/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181106065722-10aee1819953/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190206173232-65e2d4e15006/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20191004110552-13f9640d40b9/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20191105084925-a882066a44e0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb h1:eBmm0M9fYhWpKZLjQUUKka/LtIxf46G4fxeEz5KJr9U=
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a h1:DcqTD9SDLc+1P/r1EmRBwnVsrOwW+kk2vWf9n+1sGhs=
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20170830134202-bb24a47a89ea/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190209173611-3b5209105503/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210309074719-68d13333faf2 h1:46ULzRKLh1CwgRq2dC5SlBzEqqNCi8rreOZnNrbqcIY=
golang.org/x/sys v0.0.0-20210309074719-68d13333faf2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2 h1:z99zHgr7hKfrUcX/KsoJk5FJfjTceCKIp96+biqP4To=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
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=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20181011042414-1f849cf54d09/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190201180003-4b09977fb922/go.mod h1:L3J43x8/uS+qIUoksaLKe6OS3nUKxOKuIFz1sl2/jx4=
google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190530194941-fb225487d101/go.mod h1:z3L6/3dTEVtUr6QSP8miRzeRqwQOioJ9I66odjN4I7s=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio=
google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs=
google.golang.org/grpc v1.18.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
google.golang.org/grpc v1.22.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw=
gopkg.in/errgo.v1 v1.0.1/go.mod h1:3NjfXwocQRYAPTq4/fzX+CwUhPRcR/azYRhj8G+LqMo=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
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=
gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8=
gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/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/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 h1:yiW+nvdHb9LVqSHQBXfZCieqV4fzYhNBql77zY0ykqs=
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637/go.mod h1:BHsqpu/nsuzkT5BpiH1EMZPLyqSMM8JbIavyFACoFNk=
gopkg.in/tucnak/telebot.v2 v2.4.1 h1:bUOFHtHhuhPekjHGe1Q1BmITvtBLdQI4yjSMC405KcU=
gopkg.in/tucnak/telebot.v2 v2.4.1/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI=
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.1.4 h1:PDzwYE+sI6De2+mxAneV9Xs11+ZyKV6oxD3wDGkaNvM=
gorm.io/driver/sqlite v1.1.4/go.mod h1:mJCeTFr7+crvS+TRnWc5Z3UvwxUN1BGBLMrf5LA9DYw=
gorm.io/gorm v1.20.7/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
@@ -317,3 +764,14 @@ gorm.io/gorm v1.21.12 h1:3fQM0Eiz7jcJEhPggHEpoYnsGZqynMzverL77DV40RM=
gorm.io/gorm v1.21.12/go.mod h1:F+OptMscr0P2F2qU97WT1WimdH9GaQPoDW7AYd5i2Y0=
honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
k8s.io/apimachinery v0.0.0-20191123233150-4c4803ed55e3 h1:FErmbNIJruD5GT2oVEjtPn5Ar5+rcWJsC8/PPUkR0s4=
k8s.io/apimachinery v0.0.0-20191123233150-4c4803ed55e3/go.mod h1:b9qmWdKlLuU9EBh+06BtLcSf/Mu89rWL33naRxs1uZg=
k8s.io/gengo v0.0.0-20190128074634-0689ccc1d7d6/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0=
k8s.io/klog v0.0.0-20181102134211-b9b56d5dfc92/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk=
k8s.io/klog v1.0.0/go.mod h1:4Bi6QPql/J/LkTDqv7R/cd3hPo4k2DG6Ptcz060Ez5I=
k8s.io/kube-openapi v0.0.0-20191107075043-30be4d16710a/go.mod h1:1TqjTSzOxsLGIKfj0lK8EeCP7K1iUG65v09OM0/WG5E=
sigs.k8s.io/structured-merge-diff v0.0.0-20190525122527-15d366b2352e/go.mod h1:wWxsB5ozmmv/SG7nM11ayaAW51xMvak/t1r0CSlcokI=
sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o=
sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU=
+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"`
}
+26
View File
@@ -0,0 +1,26 @@
package database
import (
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/str"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
)
func MigrateAnonIdHash(db *gorm.DB) error {
users := []lnbits.User{}
_ = db.Find(&users)
for _, u := range users {
log.Info(u.ID, str.Int32Hash(u.ID))
u.AnonID = fmt.Sprint(str.Int32Hash(u.ID))
tx := db.Save(u)
if tx.Error != nil {
errmsg := fmt.Sprintf("[MigrateAnonIdHash] Error: Couldn't migrate user %s (%d)", u.Telegram.Username, u.Telegram.ID)
log.Errorln(errmsg)
return tx.Error
}
}
return nil
}
+3
View File
@@ -23,6 +23,9 @@ func RegisterLanguages() *i18n.Bundle {
bundle.LoadMessageFile("translations/nl.toml")
bundle.LoadMessageFile("translations/fr.toml")
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 {
+28 -6
View File
@@ -2,12 +2,17 @@ package lnbits
import (
"github.com/imroc/req"
"time"
)
// NewClient returns a new lnbits api client. Pass your API key and url here.
func NewClient(key, url string) *Client {
return &Client{
url: url,
// info: this header holds the ADMIN key for the entire API
// it can be used to create wallets for example
// if you want to check the balance of a user, use w.Inkey
// if you want to make a payment, use w.Adminkey
header: req.Header{
"Content-Type": "application/json",
"Accept": "application/json",
@@ -79,8 +84,13 @@ func (c *Client) CreateWallet(userId, walletName, adminId string) (wal Wallet, e
// Invoice creates an invoice associated with this wallet.
func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx BitInvoice, err error) {
c.header["X-Api-Key"] = w.Adminkey
resp, err := req.Post(c.url+"/api/v1/payments", c.header, req.BodyJSON(&params))
// custom header with invoice key
invoiceHeader := req.Header{
"Content-Type": "application/json",
"Accept": "application/json",
"X-Api-Key": w.Inkey,
}
resp, err := req.Post(c.url+"/api/v1/payments", invoiceHeader, req.BodyJSON(&params))
if err != nil {
return
}
@@ -98,8 +108,13 @@ func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx BitInvoice, err e
// Info returns wallet information
func (c Client) Info(w Wallet) (wtx Wallet, err error) {
c.header["X-Api-Key"] = w.Adminkey
resp, err := req.Get(c.url+"/api/v1/wallet", c.header, nil)
// custom header with invoice key
invoiceHeader := req.Header{
"Content-Type": "application/json",
"Accept": "application/json",
"X-Api-Key": w.Inkey,
}
resp, err := req.Get(c.url+"/api/v1/wallet", invoiceHeader, nil)
if err != nil {
return
}
@@ -135,8 +150,15 @@ func (c Client) Wallets(w User) (wtx []Wallet, err error) {
// Pay pays a given invoice with funds from the wallet.
func (w Wallet) Pay(params PaymentParams, c *Client) (wtx BitInvoice, err error) {
c.header["X-Api-Key"] = w.Adminkey
resp, err := req.Post(c.url+"/api/v1/payments", c.header, req.BodyJSON(&params))
// custom header with admin key
adminHeader := req.Header{
"Content-Type": "application/json",
"Accept": "application/json",
"X-Api-Key": w.Adminkey,
}
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
}
+13 -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 {
@@ -24,6 +24,7 @@ type User struct {
StateData string `json:"stateData"`
CreatedAt time.Time `json:"created"`
UpdatedAt time.Time `json:"updated"`
AnonID string `jsin:"anonid"`
}
const (
@@ -31,6 +32,17 @@ const (
UserStateConfirmSend
UserStateLNURLEnterAmount
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)
}
}
+61 -53
View File
@@ -3,34 +3,31 @@ package lnurl
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"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) {
@@ -42,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)
@@ -60,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)
@@ -79,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)},
@@ -117,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)},
@@ -126,16 +118,25 @@ func (w Server) serveLNURLpSecond(username string, amount int64, comment string)
// now check for the user
user := &lnbits.User{}
tx := w.database.Where("telegram_username = ?", strings.ToLower(username)).First(user)
// check if "username" is actually the user ID
tx := w.database
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
// asume it's a user ID
tx = w.database.Where("anon_id = ?", username).First(user)
} else {
// assume it's a string @username
tx = w.database.Where("telegram_username = ? COLLATE NOCASE", username).First(user)
}
if tx.Error != nil {
return &lnurl.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.")},
@@ -144,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)
@@ -154,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
@@ -190,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
}
@@ -203,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()),
}
}
+4 -3
View File
@@ -2,12 +2,13 @@ package lnurl
import (
"encoding/json"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"net/http"
"net/url"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/gorilla/mux"
@@ -32,7 +33,7 @@ const (
lnurlEndpoint = ".well-known/lnurlp"
minSendable = 1000 // mSat
MaxSendable = 1_000_000_000
CommentAllowed = 256
CommentAllowed = 500
)
func NewServer(bot *telegram.TipBot) *Server {
+23 -16
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)
@@ -94,12 +93,16 @@ func (p *PriceWatcher) GetCoinbasePrice(currency string) (float64, error) {
return 0, err
}
price := gjson.Get(string(bodyBytes), "data.amount")
fprice, err := strconv.ParseFloat(strings.TrimSpace(price.String()), 64)
if err != nil {
log.Debug(err)
return 0, err
if len(price.String()) > 0 {
fprice, err := strconv.ParseFloat(strings.TrimSpace(price.String()), 64)
if err != nil {
log.Debug(err)
return 0, err
}
return fprice, nil
} else {
return 0, fmt.Errorf("no price")
}
return fprice, nil
}
func (p *PriceWatcher) GetBitfinexPrice(currency string) (float64, error) {
@@ -107,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)
@@ -116,10 +119,14 @@ func (p *PriceWatcher) GetBitfinexPrice(currency string) (float64, error) {
return 0, err
}
price := gjson.Get(string(bodyBytes), "last_price")
fprice, err := strconv.ParseFloat(strings.TrimSpace(price.String()), 64)
if err != nil {
log.Debug(err)
return 0, err
if len(price.String()) > 0 {
fprice, err := strconv.ParseFloat(strings.TrimSpace(price.String()), 64)
if err != nil {
log.Debug(err)
return 0, err
}
return fprice, nil
} else {
return 0, fmt.Errorf("no price")
}
return fprice, nil
}
+88
View File
@@ -0,0 +1,88 @@
package rate
import (
"context"
"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.25), 20)
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 *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 {
idLimiter.GetLimiter(id).Wait(context.Background())
}
}
// 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
}
+76
View File
@@ -0,0 +1,76 @@
package runtime
import (
cmap "github.com/orcaman/concurrent-map"
"time"
)
var tickerMap cmap.ConcurrentMap
func init() {
tickerMap = cmap.New()
}
var defaultTickerCoolDown = time.Second * 10
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
type ResettableFunctionTicker struct {
Ticker *time.Ticker
ResetChan chan struct{} // channel used to reset the ticker
duration time.Duration
Started bool
name string
}
type ResettableFunctionTickerOption func(*ResettableFunctionTicker)
func WithDuration(d time.Duration) ResettableFunctionTickerOption {
return func(a *ResettableFunctionTicker) {
a.duration = d
}
}
func RemoveTicker(name string) {
tickerMap.Remove(name)
}
func GetTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
if t, ok := tickerMap.Get(name); ok {
return t.(*ResettableFunctionTicker)
} else {
t := NewResettableFunctionTicker(name, option...)
tickerMap.Set(name, t)
return t
}
}
func NewResettableFunctionTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
t := &ResettableFunctionTicker{
ResetChan: make(chan struct{}, 1),
name: name,
}
for _, opt := range option {
opt(t)
}
if t.duration == 0 {
t.duration = defaultTickerCoolDown
}
t.Ticker = time.NewTicker(t.duration)
return t
}
func (t *ResettableFunctionTicker) Do(f func()) {
t.Started = true
tickerMap.Set(t.name, t)
go func() {
for {
select {
case <-t.Ticker.C:
// ticker delivered signal. do function f
f()
return
case <-t.ResetChan:
// reset signal received. creating new ticker.
t.Ticker = time.NewTicker(t.duration)
}
}
}()
}
+95
View File
@@ -0,0 +1,95 @@
package mutex
import (
"context"
"fmt"
"sync"
cmap "github.com/orcaman/concurrent-map"
log "github.com/sirupsen/logrus"
)
var mutexMap cmap.ConcurrentMap
func init() {
mutexMap = cmap.New()
}
// checkSoftLock checks in mutexMap how often an existing mutex was already SoftLocked.
// The counter is there to avoid multiple recursive locking of an object in the mutexMap.
// This happens if multiple handlers call each other and try to lock/unlock multiple times
// the same mutex.
func checkSoftLock(s string) int {
if v, ok := mutexMap.Get(fmt.Sprintf("nLocks:%s", s)); ok {
return v.(int)
}
return 0
}
// LockWithContext locks a mutex only if it hasn't been locked before in a context.
// LockWithContext should be used to lock objects like faucets etc.
// The context carries a uid that is unique the each request (message, button press, etc.).
// If the uid has a lock already *for a certain object*, it increments the
// nLocks in the mutexMap. If not, it locks the object. This is supposed to lock only if nLock == 0.
func LockWithContext(ctx context.Context, s string) {
uid := ctx.Value("uid").(string)
// sync mutex to sync checkSoftLock with the increment of nLocks
// same user can't lock the same object multiple times
Lock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
var nLocks = checkSoftLock(uid)
if nLocks == 0 {
Lock(s)
} else {
log.Tracef("[Mutex] Skip lock (nLocks: %d)", nLocks)
}
nLocks++
mutexMap.Set(fmt.Sprintf("nLocks:%s", uid), nLocks)
Unlock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
}
// UnlockWithContext unlock a mutex only if it has been locked once within a context.
// If it has been locked more than once
// it only decrements nLocks and skips the unlock of the mutex. This is supposed to unlock only for
// nLocks == 1
func UnlockWithContext(ctx context.Context, s string) {
uid := ctx.Value("uid").(string)
Lock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
var nLocks = checkSoftLock(uid)
nLocks--
mutexMap.Set(fmt.Sprintf("nLocks:%s", uid), nLocks)
if nLocks == 0 {
Unlock(s)
} else {
log.Tracef("[Mutex] Skip unlock (nLocks: %d)", nLocks)
}
Unlock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
mutexMap.Remove(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
}
// Lock locks a mutex in the mutexMap. If the mutex is already in the map, it locks the current call.
// After it another call unlocks the mutex (and deletes it from the mutexMap) the mutex written again into the mutexMap.
// If the mutex was not in the mutexMap before, a new mutext is created and locked and written into the mutexMap.
func Lock(s string) {
log.Tracef("[Mutex] Attempt Lock %s", s)
if m, ok := mutexMap.Get(s); ok {
m.(*sync.Mutex).Lock()
mutexMap.Set(s, m)
} else {
m := &sync.Mutex{}
m.Lock()
mutexMap.Set(s, m)
}
log.Tracef("[Mutex] Locked %s", s)
}
// Unlock unlocks a mutex in the mutexMap.
func Unlock(s string) {
if m, ok := mutexMap.Get(s); ok {
mutexMap.Remove(s)
m.(*sync.Mutex).Unlock()
log.Tracef("[Mutex] Unlocked %s", s)
} else {
// this should never happen. Mutex should have been in the mutexMap.
log.Errorf("[Mutex] ⚠⚠⚠️ Unlock %s not in mutexMap. Skip.", s)
}
}
+49
View File
@@ -0,0 +1,49 @@
package once
import (
"fmt"
cmap "github.com/orcaman/concurrent-map"
log "github.com/sirupsen/logrus"
)
var onceMap cmap.ConcurrentMap
func init() {
onceMap = cmap.New()
}
func New(objectKey string) {
onceMap.Set(objectKey, cmap.New())
}
// Once creates a map of keys k1 with a map of keys k2.
// The idea is that an object with ID k1 can create a list of users k2
// that have already interacted with the object. If the user k2 is in the list,
// the object is not allowed to accessed again.
func Once(k1, k2 string) error {
i, ok := onceMap.Get(k1)
if ok {
return setOrReturn(i.(cmap.ConcurrentMap), k2)
}
userMap := cmap.New()
onceMap.Set(k1, userMap)
log.Tracef("[Once] Added key %s to onceMap (len=%d)", k1, len(onceMap.Keys()))
return setOrReturn(userMap, k2)
}
// setOrReturn sets the key k2 in the map i if it is not already set.
func setOrReturn(objectMap cmap.ConcurrentMap, k2 string) error {
if _, ok := objectMap.Get(k2); ok {
return fmt.Errorf("%s already consumed object", k2)
}
objectMap.Set(k2, true)
return nil
}
// Remove removes the key k1 from the map. Should be called after Once was called and
// the object k1 finished.
func Remove(k1 string) {
onceMap.Remove(k1)
log.Tracef("[Once] Removed key %s from onceMap (len=%d)", k1, len(onceMap.Keys()))
}
+91
View File
@@ -0,0 +1,91 @@
package storage
import (
"time"
"github.com/eko/gocache/store"
gocache "github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
)
var transactionCache = store.NewGoCache(gocache.New(5*time.Minute, 10*time.Minute), nil)
type Base struct {
ID string `json:"id"`
Active bool `json:"active"`
Canceled bool `json:"canceled"`
CreatedAt time.Time `json:"created"`
UpdatedAt time.Time `json:"updated"`
}
type Option func(b *Base)
func ID(id string) Option {
return func(btx *Base) {
btx.ID = id
}
}
func New(opts ...Option) *Base {
btx := &Base{
Active: true,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
for _, opt := range opts {
opt(btx)
}
return btx
}
func (tx Base) Key() string {
return tx.ID
}
func (tx *Base) Inactivate(s Storable, db *DB) error {
tx.Active = false
err := tx.Set(s, db)
if err != nil {
log.Tracef("[Bunt Inactivate] %s Error: %s", tx.ID, err.Error())
return err
}
log.Tracef("[Bunt Inactivate] %s", tx.ID)
return nil
}
func (tx *Base) Get(s Storable, db *DB) (Storable, error) {
cacheTx, err := transactionCache.Get(s.Key())
if err != nil {
err := db.Get(s)
if err != nil {
return s, err
}
log.Tracef("[Bunt] get object %s", s.Key())
return s, transactionCache.Set(s.Key(), s, &store.Options{Expiration: 5 * time.Minute})
}
log.Tracef("[Bunt Cache] get object %s", s.Key())
return cacheTx.(Storable), err
}
func (tx *Base) Set(s Storable, db *DB) error {
tx.UpdatedAt = time.Now()
err := db.Set(s)
if err != nil {
log.Errorf("[Bunt] could not set object: %v", err.Error())
return err
}
log.Tracef("[Bunt] set object %s", s.Key())
err = transactionCache.Set(s.Key(), s, &store.Options{Expiration: 5 * time.Minute})
if err != nil {
log.Errorf("[Bunt Cache] could not set object: %v", err.Error())
}
log.Tracef("[Bunt Cache] set object: %s", s.Key())
return err
}
func (tx *Base) Delete(s Storable, db *DB) error {
tx.UpdatedAt = time.Now()
return db.Delete(s.Key(), s)
}
+23 -15
View File
@@ -2,7 +2,7 @@ package storage
import (
"encoding/json"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
log "github.com/sirupsen/logrus"
"github.com/tidwall/buntdb"
)
@@ -78,23 +78,31 @@ func (db *DB) Set(object Storable) error {
}
// Delete a storable item.
// todo -- not ascend users index
func (db *DB) Delete(index string, object Storable) error {
return db.Update(func(tx *buntdb.Tx) error {
var delkeys []string
runtime.IgnoreError(
tx.Ascend(index, func(key, value string) bool {
if key == object.Key() {
delkeys = append(delkeys, key)
}
return true
}),
)
for _, k := range delkeys {
if _, err := tx.Delete(k); err != nil {
return err
}
_, err := tx.Get(object.Key())
if err != nil {
return err
}
if _, err := tx.Delete(object.Key()); err != nil {
return err
}
// OLD: from gohumble:
// todo -- not ascend users index
// var delkeys []string
// runtime.IgnoreError(
// tx.Ascend(index, func(key, value string) bool {
// if key == object.Key() {
// delkeys = append(delkeys, key)
// }
// return true
// }),
// )
// for _, k := range delkeys {
// if _, err := tx.Delete(k); err != nil {
// return err
// }
// }
return nil
})
}
@@ -1,98 +0,0 @@
package transaction
import (
"fmt"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
)
type Base struct {
ID string `json:"id"`
Active bool `json:"active"`
InTransaction bool `json:"intransaction"`
CreatedAt time.Time `json:"created"`
UpdatedAt time.Time `json:"updated"`
}
type Option func(b *Base)
func ID(id string) Option {
return func(btx *Base) {
btx.ID = id
}
}
func New(opts ...Option) *Base {
btx := &Base{
Active: true,
InTransaction: false,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
for _, opt := range opts {
opt(btx)
}
return btx
}
func (tx Base) Key() string {
return tx.ID
}
func (tx *Base) Lock(s storage.Storable, db *storage.DB) error {
// immediatelly set intransaction to block duplicate calls
tx.InTransaction = true
err := tx.Set(s, db)
if err != nil {
return err
}
return nil
}
func (tx *Base) Release(s storage.Storable, db *storage.DB) error {
// immediatelly set intransaction to block duplicate calls
tx.InTransaction = false
err := tx.Set(s, db)
if err != nil {
return err
}
return nil
}
func (tx *Base) Inactivate(s storage.Storable, db *storage.DB) error {
tx.Active = false
err := tx.Set(s, db)
if err != nil {
return err
}
return nil
}
func (tx *Base) Get(s storage.Storable, db *storage.DB) (storage.Storable, error) {
err := db.Get(s)
if err != nil {
return s, err
}
// to avoid race conditions, we block the call if there is
// already an active transaction by loop until InTransaction is false
ticker := time.NewTicker(time.Second * 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)
}
+13
View File
@@ -2,6 +2,7 @@ package str
import (
"fmt"
"hash/fnv"
"strings"
)
@@ -25,3 +26,15 @@ func MarkdownEscape(s string) string {
}
return s
}
func Int32Hash(s string) uint32 {
h := fnv.New32a()
h.Write([]byte(s))
return h.Sum32()
}
func Int64Hash(s string) uint64 {
h := fnv.New64a()
h.Write([]byte(s))
return h.Sum64()
}
+167 -9
View File
@@ -1,12 +1,21 @@
package telegram
import (
"context"
"encoding/json"
"errors"
"fmt"
"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"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func getArgumentFromCommand(input string, which int) (output string, err error) {
@@ -17,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)
@@ -27,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
}
@@ -54,20 +63,169 @@ 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
}
if amount < 1 {
errmsg := "error: Amount must be greater than 0"
// log.Errorln(errmsg)
return 0, errors.New(errmsg)
if amount <= 0 {
return 0, errors.New("amount must be greater than 0")
}
return amount, err
}
type EnterAmountStateData struct {
ID string `json:"ID"` // holds the ID of the tx object in bunt db
Type string `json:"Type"` // holds type of the tx in bunt db (needed for type checking)
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) askForAmount(ctx context.Context, id string, eventType string, amountMin int64, amountMax int64, originalCommand string) (enterAmountStateData *EnterAmountStateData, err error) {
user := LoadUser(ctx)
if user.Wallet == nil {
return // errors.New("user has no wallet"), 0
}
enterAmountStateData = &EnterAmountStateData{
ID: id,
Type: eventType,
AmountMin: amountMin,
AmountMax: amountMax,
OiringalCommand: originalCommand,
}
// 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, "enterAmountMessage")
if amountMin > 0 && amountMax >= amountMin {
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)
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) enterAmountHandler(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.UserEnterAmount) {
ResetUserState(user, bot)
return // errors.New("user state does not match"), 0
}
var EnterAmountStateData EnterAmountStateData
err := json.Unmarshal([]byte(user.StateData), &EnterAmountStateData)
if err != nil {
log.Errorf("[enterAmountHandler] %s", err.Error())
ResetUserState(user, bot)
return
}
amount, err := getAmount(m.Text)
if err != nil {
log.Warnf("[enterAmountHandler] %s", err.Error())
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
ResetUserState(user, bot)
return //err, 0
}
// amount not in allowed range from LNURL
if EnterAmountStateData.AmountMin > 0 && EnterAmountStateData.AmountMax >= EnterAmountStateData.AmountMin && // this line checks whether min_max is set at all
(amount > int64(EnterAmountStateData.AmountMax/1000) || amount < int64(EnterAmountStateData.AmountMin/1000)) { // this line then checks whether the amount is in the range
err = fmt.Errorf("amount not in range")
log.Warnf("[enterAmountHandler] %s", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), EnterAmountStateData.AmountMin/1000, EnterAmountStateData.AmountMax/1000))
ResetUserState(user, bot)
return
}
// find out which type the object in bunt has waiting for an amount
// we stored this in the EnterAmountStateData before
switch EnterAmountStateData.Type {
case "LnurlPayState":
tx := &LnurlPayState{Base: 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
}
LnurlPayState := sn.(*LnurlPayState)
LnurlPayState.Amount = amount * 1000 // mSat
// add result to persistent struct
runtime.IgnoreError(LnurlPayState.Set(LnurlPayState, 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.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, "")
bot.invoiceHandler(ctx, m)
return
case "CreateDonationState":
m.Text = fmt.Sprintf("/donate %d", amount)
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
bot.donationHandler(ctx, m)
return
case "CreateSendState":
splits := strings.SplitAfterN(EnterAmountStateData.OiringalCommand, " ", 2)
if len(splits) > 1 {
m.Text = fmt.Sprintf("/send %d %s", amount, splits[1])
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
bot.sendHandler(ctx, m)
return
}
return
default:
ResetUserState(user, bot)
return
}
// // reset database entry
// ResetUserState(user, bot)
// return
}
+2 -2
View File
@@ -6,7 +6,7 @@ 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) {
@@ -15,7 +15,7 @@ func (bot TipBot) balanceHandler(ctx context.Context, m *tb.Message) {
// reply only in private message
if m.Chat.Type != tb.ChatPrivate {
// delete message
NewMessage(m, WithDuration(0, bot.Telegram))
bot.tryDeleteMessage(m)
}
// first check whether the user is initialized
user := LoadUser(ctx)
+24 -7
View File
@@ -2,24 +2,34 @@ package telegram
import (
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"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 {
*store.GoCacheStore
}
var (
@@ -29,14 +39,19 @@ var (
// NewBot migrates data and creates a new bot
func NewBot() TipBot {
gocacheClient := gocache.New(5*time.Minute, 10*time.Minute)
gocacheStore := store.NewGoCache(gocacheClient, nil)
// create sqlite databases
db, txLogger := migration()
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},
}
}
@@ -67,7 +82,7 @@ func (bot TipBot) initBotWallet() error {
}
// Start will initialize the Telegram bot and lnbits.
func (bot TipBot) Start() {
func (bot *TipBot) Start() {
log.Infof("[Telegram] Authorized on account @%s", bot.Telegram.Me.Username)
// initialize the bot wallet
err := bot.initBotWallet()
@@ -75,5 +90,7 @@ func (bot TipBot) Start() {
log.Errorf("Could not initialize bot wallet: %s", err.Error())
}
bot.registerTelegramHandlers()
initInvoiceEventCallbacks(bot)
initializeStateCallbackMessage(bot)
bot.Telegram.Start()
}
+47
View File
@@ -0,0 +1,47 @@
package telegram
import tb "gopkg.in/lightningtipbot/telebot.v2"
// we can't use space in the label of buttons, because string splitting will mess everything up.
const (
CommandSend = "💸 Send"
CommandBalance = "👑 Balance"
CommandInvoice = "⚡️ Invoice"
CommandHelp = "📖 Help"
)
var (
mainMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
btnHelpMainMenu = mainMenu.Text(CommandHelp)
btnSendMainMenu = mainMenu.Text(CommandSend)
btnBalanceMainMenu = mainMenu.Text(CommandBalance)
btnInvoiceMainMenu = mainMenu.Text(CommandInvoice)
)
func init() {
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu, btnHelpMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu),
)
}
// buttonWrapper wrap buttons slice in rows of length i
func buttonWrapper(buttons []tb.Btn, markup *tb.ReplyMarkup, length int) []tb.Row {
buttonLength := len(buttons)
rows := make([]tb.Row, 0)
if buttonLength > length {
for i := 0; i < buttonLength; i = i + length {
buttonRow := make([]tb.Btn, length)
if i+length < buttonLength {
buttonRow = buttons[i : i+length]
} else {
buttonRow = buttons[i:]
}
rows = append(rows, markup.Row(buttonRow...))
}
return rows
}
rows = append(rows, markup.Row(buttons...))
return rows
}
+81 -30
View File
@@ -2,18 +2,21 @@ package telegram
import (
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/tidwall/buntdb"
"reflect"
"strconv"
"strings"
"time"
"github.com/eko/gocache/store"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/database"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/tidwall/buntdb"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
@@ -23,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 {
@@ -33,21 +36,41 @@ func createBunt() *storage.DB {
}
return bunt
}
func migration() (db *gorm.DB, txLogger *gorm.DB) {
txLogger, err := gorm.Open(sqlite.Open(internal.Configuration.Database.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
if err != nil {
panic("Initialize orm failed.")
}
func ColumnMigrationTasks(db *gorm.DB) error {
var err error
if !db.Migrator().HasColumn(&lnbits.User{}, "anon_id") {
// first we need to auto migrate the user. This will create anon_id column
err = db.AutoMigrate(&lnbits.User{})
if err != nil {
panic(err)
}
log.Info("Running ano_id database migrations ...")
// run the migration on anon_id
err = database.MigrateAnonIdHash(db)
}
// todo -- add more database field migrations here in the future
return err
}
func AutoMigration() (db *gorm.DB, txLogger *gorm.DB) {
orm, err := gorm.Open(sqlite.Open(internal.Configuration.Database.DbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
if err != nil {
panic("Initialize orm failed.")
}
err = ColumnMigrationTasks(orm)
if err != nil {
panic(err)
}
err = orm.AutoMigrate(&lnbits.User{})
if err != nil {
panic(err)
}
txLogger, err = gorm.Open(sqlite.Open(internal.Configuration.Database.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
if err != nil {
panic("Initialize orm failed.")
}
err = txLogger.AutoMigrate(&Transaction{})
if err != nil {
panic(err)
@@ -57,7 +80,11 @@ func migration() (db *gorm.DB, txLogger *gorm.DB) {
func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.User, error) {
toUserDb := &lnbits.User{}
tx := bot.Database.Where("telegram_username = ?", strings.ToLower(toUserStrWithoutAt)).First(toUserDb)
// return error if username is too long
if len(toUserStrWithoutAt) > 100 {
return nil, fmt.Errorf("[GetUserByTelegramUsername] Telegram username is too long: %s..", toUserStrWithoutAt[:100])
}
tx := bot.Database.Where("telegram_username = ? COLLATE NOCASE", toUserStrWithoutAt).First(toUserDb)
if tx.Error != nil || toUserDb.Wallet == nil {
err := tx.Error
if toUserDb.Wallet == nil {
@@ -67,6 +94,14 @@ 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.FormatInt(u.ID, 10)}
if us, err := bot.Cache.Get(user.Name); err == nil {
return us.(*lnbits.User), nil
}
user.Telegram = u
return user, gorm.ErrRecordNotFound
}
// GetLnbitsUser will not update the user in Database.
// this is required, because fetching lnbits.User from a incomplete tb.User
@@ -75,7 +110,7 @@ func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.U
// &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())
@@ -83,31 +118,44 @@ func GetLnbitsUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
user.Telegram = u
return user, tx.Error
}
// todo -- unblock this !
return user, nil
}
// GetUser from Telegram user. Update the user if user information changed.
func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
user, err := GetLnbitsUser(u, bot)
if err != nil {
return user, err
}
go func() {
userCopy := bot.copyLowercaseUser(u)
if !reflect.DeepEqual(userCopy, user.Telegram) {
// update possibly changed user details in Database
user.Telegram = userCopy
err = UpdateUserRecord(user, bot)
if err != nil {
log.Warnln(fmt.Sprintf("[UpdateUserRecord] %s", err.Error()))
}
var user *lnbits.User
var err error
if user, err = getCachedUser(u, bot); err != nil {
user, err = GetLnbitsUser(u, bot)
if err != nil {
return user, err
}
}()
updateCachedUser(user, bot)
}
if telegramUserChanged(u, user.Telegram) {
// update possibly changed user details in Database
user.Telegram = u
err = UpdateUserRecord(user, bot)
if err != nil {
log.Warnln(fmt.Sprintf("[UpdateUserRecord] %s", err.Error()))
}
}
return user, err
}
func updateCachedUser(apiUser *lnbits.User, bot TipBot) {
bot.Cache.Set(apiUser.Name, apiUser, &store.Options{Expiration: 1 * time.Minute})
}
func telegramUserChanged(apiUser, stateUser *tb.User) bool {
if reflect.DeepEqual(apiUser, stateUser) {
return false
}
return true
}
func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
user.Telegram = bot.copyLowercaseUser(user.Telegram)
user.UpdatedAt = time.Now()
tx := bot.Database.Save(user)
if tx.Error != nil {
@@ -116,5 +164,8 @@ func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
return tx.Error
}
log.Debugf("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
if bot.Cache.GoCacheStore != nil {
updateCachedUser(user, bot)
}
return nil
}
+14 -15
View File
@@ -3,15 +3,16 @@ package telegram
import (
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
// PLEASE DO NOT CHANGE THE CODE IN THIS FILE
@@ -34,24 +35,22 @@ func helpDonateUsage(ctx context.Context, errormsg string) string {
func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) {
// check and print all commands
bot.anyTextHandler(ctx, m)
if len(strings.Split(m.Text, " ")) < 2 {
bot.trySendMessage(m.Sender, helpDonateUsage(ctx, Translate(ctx, "donateEnterAmountMessage")))
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
// if no amount is in the command, ask for it
amount, err := decodeAmountFromCommand(m.Text)
if err != nil {
return
}
if amount < 1 {
bot.trySendMessage(m.Sender, helpDonateUsage(ctx, Translate(ctx, "donateValidAmountMessage")))
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
// // no amount was entered, set user state and ask for amount
bot.askForAmount(ctx, "", "CreateDonationState", 0, 0, m.Text)
return
}
// command is valid
msg := bot.trySendMessage(m.Sender, Translate(ctx, "donationProgressMessage"))
msg := bot.trySendMessage(m.Chat, Translate(ctx, "donationProgressMessage"))
// get invoice
resp, err := http.Get(fmt.Sprintf(donationEndpoint, amount, GetUserStr(m.Sender), GetUserStr(bot.Telegram.Me)))
resp, err := http.Get(fmt.Sprintf(donationEndpoint, amount, GetUserStr(user.Telegram), GetUserStr(bot.Telegram.Me)))
if err != nil {
log.Errorln(err)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
@@ -65,14 +64,14 @@ func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) {
}
// send donation invoice
user := LoadUser(ctx)
// user := LoadUser(ctx)
// bot.trySendMessage(user.Telegram, string(body))
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: string(body)}, bot.Client)
if err != nil {
userStr := GetUserStr(m.Sender)
userStr := GetUserStr(user.Telegram)
errmsg := fmt.Sprintf("[/donate] Donation failed for user %s: %s", userStr, err)
log.Errorln(errmsg)
bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "donationFailedMessage"), err))
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return
}
bot.tryEditMessage(msg, Translate(ctx, "donationSuccess"))
+32
View File
@@ -0,0 +1,32 @@
package telegram
import (
"context"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func (bot *TipBot) fileHandler(ctx context.Context, m *tb.Message) {
if m.Chat.Type != tb.ChatPrivate {
return
}
user := LoadUser(ctx)
if c := stateCallbackMessage[user.StateKey]; c != nil {
// found handler for this state
// now looking for user state reset ticker
ticker := runtime.GetTicker(user.ID)
if !ticker.Started {
ticker.Do(func() {
ResetUserState(user, bot)
// removing ticker asap done
bot.shopViewDeleteAllStatusMsgs(ctx, user, 0)
runtime.RemoveTicker(user.ID)
})
} else {
ticker.ResetChan <- struct{}{}
}
c(ctx, m)
return
}
}
File diff suppressed because it is too large Load Diff
+24 -25
View File
@@ -4,17 +4,18 @@ 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 {
fromUser := LoadUser(ctx)
dynamicHelpMessage := ""
// user has no username set
if len(m.Sender.Username) == 0 {
// return fmt.Sprintf(helpMessage, fmt.Sprintf("%s\n\n", helpNoUsernameMessage))
dynamicHelpMessage = dynamicHelpMessage + "\n" + Translate(ctx, "helpNoUsernameMessage")
}
lnaddr, _ := bot.UserGetLightningAddress(m.Sender)
lnaddr, _ := bot.UserGetLightningAddress(fromUser)
if len(lnaddr) > 0 {
dynamicHelpMessage = dynamicHelpMessage + "\n" + fmt.Sprintf(Translate(ctx, "infoYourLightningAddress"), lnaddr)
}
@@ -30,7 +31,7 @@ func (bot TipBot) helpHandler(ctx context.Context, m *tb.Message) {
bot.anyTextHandler(ctx, m)
if !m.Private() {
// delete message
NewMessage(m, WithDuration(0, bot.Telegram))
bot.tryDeleteMessage(m)
}
bot.trySendMessage(m.Sender, bot.makeHelpMessage(ctx, m), tb.NoPreview)
return
@@ -41,38 +42,36 @@ func (bot TipBot) basicsHandler(ctx context.Context, m *tb.Message) {
bot.anyTextHandler(ctx, m)
if !m.Private() {
// delete message
NewMessage(m, WithDuration(0, bot.Telegram))
bot.tryDeleteMessage(m)
}
bot.trySendMessage(m.Sender, Translate(ctx, "basicsMessage"), tb.NoPreview)
return
}
func (bot TipBot) makeAdvancedHelpMessage(ctx context.Context, m *tb.Message) string {
dynamicHelpMessage := ""
fromUser := LoadUser(ctx)
dynamicHelpMessage := "ℹ️ *Info*\n"
// user has no username set
if len(m.Sender.Username) == 0 {
// return fmt.Sprintf(helpMessage, fmt.Sprintf("%s\n\n", helpNoUsernameMessage))
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("%s", Translate(ctx, "helpNoUsernameMessage"))
} else {
dynamicHelpMessage = "ℹ️ *Info*\n"
lnaddr, err := bot.UserGetLightningAddress(m.Sender)
if err != nil {
dynamicHelpMessage = ""
} else {
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Your Lightning Address:\n`%s`\n", lnaddr)
}
lnurl, err := UserGetLNURL(m.Sender)
if err != nil {
dynamicHelpMessage = ""
} else {
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Your LNURL:\n`%s`", lnurl)
}
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("%s", Translate(ctx, "helpNoUsernameMessage")) + "\n"
}
// we print the anonymous ln address in the advanced help
lnaddr, err := bot.UserGetAnonLightningAddress(fromUser)
if err == nil {
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Anonymous lightning address: `%s`\n", lnaddr)
}
lnurl, err := UserGetLNURL(fromUser)
if err == nil {
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("LNURL: `%s`", lnurl)
}
// this is so stupid:
return fmt.Sprintf(Translate(ctx, "advancedMessage"), dynamicHelpMessage, GetUserStr(bot.Telegram.Me), GetUserStr(bot.Telegram.Me), GetUserStr(bot.Telegram.Me))
return fmt.Sprintf(
Translate(ctx, "advancedMessage"),
dynamicHelpMessage,
GetUserStr(bot.Telegram.Me),
)
}
func (bot TipBot) advancedHelpHandler(ctx context.Context, m *tb.Message) {
@@ -80,7 +79,7 @@ func (bot TipBot) advancedHelpHandler(ctx context.Context, m *tb.Message) {
bot.anyTextHandler(ctx, m)
if !m.Private() {
// delete message
NewMessage(m, WithDuration(0, bot.Telegram))
bot.tryDeleteMessage(m)
}
bot.trySendMessage(m.Sender, bot.makeAdvancedHelpMessage(ctx, m), tb.NoPreview)
return
+9 -1
View File
@@ -34,10 +34,18 @@ 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))
progressbar += strings.Repeat("⬜️", MAX_BARS-int(progress))
return progressbar
}
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))
progressbar += strings.Repeat("⬜️", MAX_BARS-int(progress))
return progressbar
}
+155 -184
View File
@@ -3,17 +3,24 @@ 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 (
@@ -22,19 +29,21 @@ var (
btnAcceptInlineFaucet = inlineFaucetMenu.Data("✅ Collect", "confirm_faucet_inline")
)
type InlineFaucet struct {
*transaction.Base
Message string `json:"inline_faucet_message"`
Amount int `json:"inline_faucet_amount"`
RemainingAmount int `json:"inline_faucet_remainingamount"`
PerUserAmount int `json:"inline_faucet_peruseramount"`
From *lnbits.User `json:"inline_faucet_from"`
To []*tb.User `json:"inline_faucet_to"`
Memo string `json:"inline_faucet_memo"`
NTotal int `json:"inline_faucet_ntotal"`
NTaken int `json:"inline_faucet_ntaken"`
UserNeedsWallet bool `json:"inline_faucet_userneedswallet"`
LanguageCode string `json:"languagecode"`
const idTemplate = "faucet-%d-%d-%s"
type Faucet struct {
*storage.Base
Message string `json:"faucet_message"`
Amount int64 `json:"faucet_amount"`
RemainingAmount int64 `json:"faucet_remainingamount"`
PerUserAmount int64 `json:"faucet_peruseramount"`
From *lnbits.User `json:"faucet_from"`
To []*lnbits.User `json:"faucet_to"`
Memo string `json:"faucet_memo"`
NTotal int `json:"faucet_ntotal"`
NTaken int `json:"faucet_ntaken"`
UserNeedsWallet bool `json:"faucet_userneedswallet"`
LanguageCode string `json:"languagecode"`
}
func (bot TipBot) mapFaucetLanguage(ctx context.Context, command string) context.Context {
@@ -45,7 +54,7 @@ func (bot TipBot) mapFaucetLanguage(ctx context.Context, command string) context
return ctx
}
func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User) (*InlineFaucet, error) {
func (bot TipBot) createFaucet(ctx context.Context, text string, inline bool, sender *tb.User) (*Faucet, error) {
amount, err := decodeAmountFromCommand(text)
if err != nil {
return nil, errors.New(errors.DecodeAmountError, err)
@@ -58,19 +67,19 @@ 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.GetUserBalance(fromUser)
balance, err := bot.GetUserBalanceCached(fromUser)
if err != nil {
return nil, errors.New(errors.GetBalanceError, err)
}
// check if fromUser has balance
if balance < amount {
return nil, errors.New(errors.BalanceToLowError, fmt.Errorf("[faucet] Balance of user %s too low: %v", fromUserStr, err))
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)
@@ -79,10 +88,14 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
if len(memo) > 0 {
inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineFaucetAppendMemo"), memo)
}
id := fmt.Sprintf("inl-faucet-%d-%d-%s", sender.ID, amount, RandStringRunes(5))
return &InlineFaucet{
Base: transaction.New(transaction.ID(id)),
id := fmt.Sprintf(idTemplate, sender.ID, amount, RandStringRunes(5))
if inline {
id = fmt.Sprintf("inl-%s", id)
}
return &Faucet{
Base: storage.New(storage.ID(id)),
Message: inlineMessage,
Amount: amount,
From: fromUser,
@@ -96,66 +109,62 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
}, nil
}
func (bot TipBot) makeFaucet(ctx context.Context, m *tb.Message, query bool) (*InlineFaucet, error) {
faucet, err := bot.createFaucet(ctx, m.Text, m.Sender)
if err != nil {
switch err.(errors.TipBotError).Code {
case errors.DecodeAmountError:
func (bot TipBot) handleFaucetError(ctx context.Context, faucet interface{}, err error) {
var m *tb.Message
var q *tb.Query
switch faucet.(type) {
case *tb.Message:
m = faucet.(*tb.Message)
case *tb.Query:
q = faucet.(*tb.Query)
}
switch err.(errors.TipBotError).Code {
case errors.DecodeAmountError:
if q != nil {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
} else if m != nil {
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidAmountMessage")))
bot.tryDeleteMessage(m)
return nil, err
case errors.DecodePerUserAmountError:
}
case errors.DecodePerUserAmountError:
if q != nil {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
} else if m != nil {
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), ""))
bot.tryDeleteMessage(m)
return nil, err
case errors.InvalidAmountError:
}
case errors.InvalidAmountError:
if q != nil {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
} else if m != nil {
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidAmountMessage")))
bot.tryDeleteMessage(m)
return nil, err
case errors.InvalidAmountPerUserError:
}
case errors.InvalidAmountPerUserError:
if q != nil {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineFaucetInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
} else if m != nil {
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidPeruserAmountMessage")))
bot.tryDeleteMessage(m)
return nil, err
case errors.GetBalanceError:
// log.Errorln(err.Error())
}
case errors.GetBalanceError:
if q != nil {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
} else if m != nil {
bot.tryDeleteMessage(m)
return nil, err
case errors.BalanceToLowError:
// log.Errorf(err.Error())
}
case errors.BalanceToLowError:
if q != nil {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
} else if m != nil {
bot.trySendMessage(m.Sender, Translate(ctx, "inlineSendBalanceLowMessage"))
bot.tryDeleteMessage(m)
return nil, err
}
}
return faucet, err
}
func (bot TipBot) makeQueryFaucet(ctx context.Context, q *tb.Query, query bool) (*InlineFaucet, error) {
faucet, err := bot.createFaucet(ctx, q.Text, &q.From)
if err != nil {
switch err.(errors.TipBotError).Code {
case errors.DecodeAmountError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.DecodePerUserAmountError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.InvalidAmountError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.InvalidAmountPerUserError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineFaucetInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.GetBalanceError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.BalanceToLowError:
log.Errorf(err.Error())
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
}
}
return faucet, err
}
func (bot TipBot) makeFaucetKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
@@ -172,16 +181,16 @@ func (bot TipBot) makeFaucetKeyboard(ctx context.Context, id string) *tb.ReplyMa
return inlineFaucetMenu
}
func (bot TipBot) faucetHandler(ctx context.Context, m *tb.Message) {
func (bot TipBot) createFaucetHandler(ctx context.Context, m *tb.Message) {
bot.anyTextHandler(ctx, m)
if m.Private() {
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetHelpFaucetInGroup")))
return
}
ctx = bot.mapFaucetLanguage(ctx, m.Text)
inlineFaucet, err := bot.makeFaucet(ctx, m, false)
inlineFaucet, err := bot.createFaucet(ctx, m.Text, false, m.Sender)
if err != nil {
log.Errorf("[faucet] %s", err)
log.Warnf("[faucet] %s", err.Error())
return
}
fromUserStr := GetUserStr(m.Sender)
@@ -190,70 +199,18 @@ func (bot TipBot) faucetHandler(ctx context.Context, m *tb.Message) {
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
}
func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
inlineFaucet, err := bot.makeQueryFaucet(ctx, q, false)
func (bot TipBot) createInlineFaucetHandler(ctx context.Context, q *tb.Query) {
inlineFaucet, err := bot.createFaucet(ctx, q.Text, true, &q.From)
if err != nil {
// log.Errorf("[faucet] %s", err)
bot.handleFaucetError(ctx, q, err)
log.Errorf("[createInlineFaucetHandler] %s", err.Error())
return
}
/**amount, err := decodeAmountFromCommand(q.Text)
if err != nil {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.telegram.Me.Username))
return
}
if amount < 1 {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.telegram.Me.Username))
return
}
peruserStr, err := getArgumentFromCommand(q.Text, 2)
if err != nil {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.telegram.Me.Username))
return
}
perUserAmount, err := getAmount(peruserStr)
if err != nil {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.telegram.Me.Username))
return
}
// peruser amount must be >1 and a divisor of amount
if perUserAmount < 1 || amount%perUserAmount != 0 {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineFaucetInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.telegram.Me.Username))
return
}
nTotal := amount / perUserAmount
fromUser := LoadUser(ctx)
fromUserStr := GetUserStr(&q.From)
balance, err := bot.GetUserBalance(fromUser)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
log.Errorln(errmsg)
return
}
// check if fromUser has balance
if balance < amount {
log.Errorf("Balance of user %s too low", fromUserStr)
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.telegram.Me.Username))
return
}
// check for memo in command
memo := GetMemoFromCommand(q.Text, 3)
**/
// faucet, err := bot.createFaucet(ctx, q.Text, &q.From)
// if err != nil {
// log.Errorf(err.Error())
// return
// }
urls := []string{
queryImage,
}
results := make(tb.Results, len(urls)) // []tb.Result
for i, url := range urls {
// inlineMessage := fmt.Sprintf(Translate(ctx, "inlineFaucetMessage"), faucet.PerUserAmount, faucet.Amount, faucet.Amount, 0, faucet.NTotal, MakeProgressbar(faucet.Amount, faucet.Amount))
// if len(faucet.Memo) > 0 {
// inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineFaucetAppendMemo"), faucet.Memo)
// }
result := &tb.ArticleResult{
// URL: url,
Text: inlineFaucet.Message,
@@ -262,28 +219,13 @@ func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
// required for photos
ThumbURL: url,
}
// id := fmt.Sprintf("inl-faucet-%d-%d-%s", q.From.ID, faucet.Amount, RandStringRunes(5))
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeFaucetKeyboard(ctx, inlineFaucet.ID).InlineKeyboard}
results[i] = result
// needed to set a unique string ID for each result
results[i].SetResultID(inlineFaucet.ID)
// create persistend inline send struct
// inlineFaucet := InlineFaucet{
// Base: transaction.New(transaction.ID(id)),
// Message: inlineMessage,
// From: faucet.From,
// Memo: faucet.Memo,
// NTaken: 0,
// Amount: faucet.Amount,
// PerUserAmount: faucet.PerUserAmount,
// RemainingAmount: faucet.Amount,
// UserNeedsWallet: false,
// LanguageCode: ctx.Value("publicLanguageCode").(string),
// }
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{
@@ -291,45 +233,49 @@ func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
CacheTime: 1,
})
if err != nil {
log.Errorln(err)
log.Errorln(err.Error())
}
}
func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) acceptFaucetHandler(ctx context.Context, c *tb.Callback) {
to := LoadUser(ctx)
tx := &InlineFaucet{Base: transaction.New(transaction.ID(c.Data))}
tx := &Faucet{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[faucet] %s", err)
log.Debugf("[acceptFaucetHandler] %s", err.Error())
return
}
inlineFaucet := fn.(*InlineFaucet)
inlineFaucet := fn.(*Faucet)
from := inlineFaucet.From
err = inlineFaucet.Lock(inlineFaucet, bot.Bunt)
if err != nil {
log.Errorf("[faucet] LockFaucet %s error: %s", inlineFaucet.ID, err)
return
// log faucet link if possible
if c.Message != nil && c.Message.Chat != nil {
log.Debugf("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(c.Message.Chat.ID, 10)[4:], c.Message.ID)
}
if !inlineFaucet.Active {
log.Errorf(fmt.Sprintf("[faucet] faucet %s inactive.", inlineFaucet.ID))
log.Debugf(fmt.Sprintf("[faucet] faucet %s inactive. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
bot.finishFaucet(ctx, c, inlineFaucet)
return
}
// release faucet no matter what
defer inlineFaucet.Release(inlineFaucet, bot.Bunt)
if from.Telegram.ID == to.Telegram.ID {
log.Debugf("[faucet] %s is the owner faucet %s", GetUserStr(to.Telegram), inlineFaucet.ID)
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
return
}
// check if to user has already taken from the faucet
for _, a := range inlineFaucet.To {
if a.ID == to.Telegram.ID {
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)
@@ -338,7 +284,6 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
// check if user exists and create a wallet if not
_, exists := bot.UserExists(to.Telegram)
if !exists {
log.Infof("[faucet] User %s has no wallet.", toUserStr)
to, err = bot.CreateWalletForTelegramUser(to.Telegram)
if err != nil {
errmsg := fmt.Errorf("[faucet] Error: Could not create wallet for %s", toUserStr)
@@ -359,23 +304,27 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
success, err := t.Send()
if !success {
bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
errMsg := fmt.Sprintf("[faucet] Transaction failed: %s", err)
log.Errorln(errMsg)
errMsg := fmt.Sprintf("[faucet] Transaction failed: %s", err.Error())
log.Warnln(errMsg)
// if faucet fails, cancel it:
// c.Sender.ID = inlineFaucet.From.Telegram.ID // overwrite the sender of the callback to be the faucet owner
// log.Debugf("[faucet] Canceling faucet %s...", inlineFaucet.ID)
// bot.cancelInlineFaucet(ctx, c, true) // cancel without ID check
return
}
log.Infof("[faucet] faucet %s: %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.Telegram)
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() {
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineFaucetReceivedMessage"), fromUserStrMd, inlineFaucet.PerUserAmount))
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineFaucetSentMessage"), inlineFaucet.PerUserAmount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[faucet] Error: Send message to %s: %s", toUserStr, err.Error())
log.Warnln(errmsg)
}
}()
// build faucet message
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetMessage"), inlineFaucet.PerUserAmount, inlineFaucet.RemainingAmount, inlineFaucet.Amount, inlineFaucet.NTaken, inlineFaucet.NTotal, MakeProgressbar(inlineFaucet.RemainingAmount, inlineFaucet.Amount))
@@ -388,34 +337,56 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
}
// update message
log.Infoln(inlineFaucet.Message)
bot.tryEditMessage(c.Message, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
// update the message if the faucet still has some sats left after this tx
if inlineFaucet.RemainingAmount >= inlineFaucet.PerUserAmount {
go func() {
bot.tryEditMessage(c.Message, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
}()
}
}
if inlineFaucet.RemainingAmount < inlineFaucet.PerUserAmount {
// faucet is depleted
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetEndedMessage"), inlineFaucet.Amount, inlineFaucet.NTaken)
if inlineFaucet.UserNeedsWallet {
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
}
bot.tryEditMessage(c.Message, inlineFaucet.Message)
inlineFaucet.Active = false
bot.finishFaucet(ctx, c, inlineFaucet)
}
}
func (bot *TipBot) cancelInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
tx := &InlineFaucet{Base: transaction.New(transaction.ID(c.Data))}
func (bot *TipBot) cancelInlineFaucet(ctx context.Context, c *tb.Callback, ignoreID bool) {
tx := &Faucet{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[cancelInlineSendHandler] %s", err)
log.Debugf("[cancelInlineFaucetHandler] %s", err.Error())
return
}
inlineFaucet := fn.(*InlineFaucet)
if c.Sender.ID == inlineFaucet.From.Telegram.ID {
inlineFaucet := fn.(*Faucet)
if ignoreID || c.Sender.ID == inlineFaucet.From.Telegram.ID {
bot.tryEditMessage(c.Message, i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage"), &tb.ReplyMarkup{})
// set the inlineFaucet inactive
inlineFaucet.Active = false
inlineFaucet.InTransaction = false
inlineFaucet.Canceled = true
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
log.Debugf("[faucet] Faucet %s canceled.", inlineFaucet.ID)
once.Remove(inlineFaucet.ID)
}
return
}
func (bot *TipBot) finishFaucet(ctx context.Context, c *tb.Callback, inlineFaucet *Faucet) {
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetEndedMessage"), inlineFaucet.Amount, inlineFaucet.NTaken)
if inlineFaucet.UserNeedsWallet {
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
}
bot.tryEditMessage(c.Message, inlineFaucet.Message, &tb.ReplyMarkup{})
inlineFaucet.Active = false
log.Debugf("[faucet] Faucet finished %s", inlineFaucet.ID)
once.Remove(inlineFaucet.ID)
}
func (bot *TipBot) cancelInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
bot.cancelInlineFaucet(ctx, c, false)
return
}
+35 -4
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"
@@ -35,6 +39,11 @@ func (bot TipBot) inlineQueryInstructions(ctx context.Context, q *tb.Query) {
title: TranslateUser(ctx, "inlineQueryFaucetTitle"),
description: fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username),
},
{
url: queryImage,
title: TranslateUser(ctx, "inlineQueryTipjarTitle"),
description: fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username),
},
}
results := make(tb.Results, len(instructions)) // []tb.Result
for i, instruction := range instructions {
@@ -86,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 {
@@ -96,7 +120,7 @@ func (bot TipBot) commandTranslationMap(ctx context.Context, command string) con
// case "faucet":
// ctx = context.WithValue(ctx, "publicLanguageCode", "en")
// ctx = context.WithValue(ctx, "publicLocalizer", i18n.NewLocalizer(i18n.Bundle, "en"))
case "zapfhahn":
case "zapfhahn", "spendendose":
ctx = context.WithValue(ctx, "publicLanguageCode", "de")
ctx = context.WithValue(ctx, "publicLocalizer", i18n2.NewLocalizer(i18n.Bundle, "de"))
case "kraan":
@@ -128,7 +152,14 @@ func (bot TipBot) anyQueryHandler(ctx context.Context, q *tb.Query) {
c := strings.Split(q.Text, " ")[0]
ctx = bot.commandTranslationMap(ctx, c)
}
bot.handleInlineFaucetQuery(ctx, q)
bot.createInlineFaucetHandler(ctx, q)
}
if strings.HasPrefix(q.Text, "tipjar") || strings.HasPrefix(q.Text, "spendendose") {
if len(strings.Split(q.Text, " ")) > 1 {
c := strings.Split(q.Text, " ")[0]
ctx = bot.commandTranslationMap(ctx, c)
}
bot.handleInlineTipjarQuery(ctx, q)
}
if strings.HasPrefix(q.Text, "receive") || strings.HasPrefix(q.Text, "get") || strings.HasPrefix(q.Text, "payme") || strings.HasPrefix(q.Text, "request") {
+202 -55
View File
@@ -1,16 +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 (
@@ -20,13 +28,15 @@ var (
)
type InlineReceive struct {
*transaction.Base
Message string `json:"inline_receive_message"`
Amount int `json:"inline_receive_amount"`
From *lnbits.User `json:"inline_receive_from"`
To *lnbits.User `json:"inline_receive_to"`
Memo string
LanguageCode string `json:"languagecode"`
*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"`
Memo string `json:"inline_receive_memo"`
LanguageCode string `json:"languagecode"`
}
func (bot TipBot) makeReceiveKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
@@ -36,14 +46,15 @@ func (bot TipBot) makeReceiveKeyboard(ctx context.Context, id string) *tb.ReplyM
cancelInlineReceiveButton.Data = id
inlineReceiveMenu.Inline(
inlineReceiveMenu.Row(
cancelInlineReceiveButton,
acceptInlineReceiveButton,
cancelInlineReceiveButton),
),
)
return inlineReceiveMenu
}
func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
from := LoadUser(ctx)
to := LoadUser(ctx)
amount, err := decodeAmountFromCommand(q.Text)
if err != nil {
bot.inlineQueryReplyWithError(q, Translate(ctx, "inlineQueryReceiveTitle"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
@@ -53,15 +64,45 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
bot.inlineQueryReplyWithError(q, Translate(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
return
}
fromUserStr := GetUserStr(&q.From)
toUserStr := GetUserStr(&q.From)
// check whether the 3rd argument is a username
// command is "@LightningTipBot receive 123 @from_user This is the memo"
memo_argn := 2 // argument index at which the memo starts, will be 3 if there is a from_username in command
fromUserDb := &lnbits.User{}
from_SpecificUser := false
if len(strings.Split(q.Text, " ")) > 2 {
from_username := strings.Split(q.Text, " ")[2]
if strings.HasPrefix(from_username, "@") {
fromUserDb, err = GetUserByTelegramUsername(from_username[1:], bot) // must be without the @
if err != nil {
//bot.tryDeleteMessage(m)
//bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), toUserStrMention))
bot.inlineQueryReplyWithError(q,
fmt.Sprintf(TranslateUser(ctx, "sendUserHasNoWalletMessage"), from_username),
fmt.Sprintf(TranslateUser(ctx, "inlineQueryReceiveDescription"),
bot.Telegram.Me.Username))
return
}
memo_argn = 3 // assume that memo starts after the from_username
from_SpecificUser = true
}
}
// check for memo in command
memo := GetMemoFromCommand(q.Text, 2)
memo := GetMemoFromCommand(q.Text, memo_argn)
urls := []string{
queryImage,
}
results := make(tb.Results, len(urls)) // []tb.Result
for i, url := range urls {
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineReceiveMessage"), fromUserStr, amount)
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineReceiveMessage"), toUserStr, amount)
// modify message if payment is to specific user
if from_SpecificUser {
inlineMessage = fmt.Sprintf("@%s: %s", fromUserDb.Telegram.Username, inlineMessage)
}
if len(memo) > 0 {
inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineReceiveAppendMemo"), memo)
}
@@ -80,16 +121,16 @@ 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,
To: from,
Memo: memo,
Amount: amount,
From: from,
LanguageCode: ctx.Value("publicLanguageCode").(string),
Base: storage.New(storage.ID(id)),
MessageText: inlineMessage,
To: to,
Memo: memo,
Amount: amount,
From: fromUserDb,
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{
@@ -103,45 +144,89 @@ 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)
if !inlineReceive.Active {
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
return
}
// user `from` is the one who is SENDING
// user `to` is the one who is RECEIVING
from := LoadUser(ctx)
// check if this payment is requested from a specific user
if inlineReceive.From_SpecificUser {
if inlineReceive.From.Telegram.ID != from.Telegram.ID {
// log.Infof("User %d is not User %d", inlineReceive.From.Telegram.ID, from.Telegram.ID)
return
}
} 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
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)
// defer inlineReceive.Release(inlineReceive, bot.Bunt)
// user `from` is the one who is SENDING
// user `to` is the one who is RECEIVING
// from := inlineReceive.From
from := LoadUser(ctx)
if from.Wallet == nil {
return
}
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 check of the user
balance, err := bot.GetUserBalance(from)
balance, err := bot.GetUserBalanceCached(from)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
log.Errorln(errmsg)
@@ -163,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))
func (bot *TipBot) inlineReceiveInvoice(ctx context.Context, c *tb.Callback, inlineReceive *InlineReceive) {
if !inlineReceive.Active {
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
return
}
invoice, err := bot.createInvoiceWithEvent(ctx, inlineReceive.To, inlineReceive.Amount, fmt.Sprintf("Pay to %s", GetUserStr(inlineReceive.To.Telegram)), InvoiceCallbackInlineReceive, inlineReceive.ID)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
bot.tryEditMessage(inlineReceive.Message, Translate(ctx, "errorTryLaterMessage"))
log.Errorln(errmsg)
return
}
// create qr code
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
bot.tryEditMessage(inlineReceive.Message, Translate(ctx, "errorTryLaterMessage"))
log.Errorln(errmsg)
return
}
// send the invoice data to user
var msg *tb.Message
if inlineReceive.Message.Chat != nil {
msg = bot.trySendMessage(inlineReceive.Message.Chat, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
} else {
msg = bot.trySendMessage(c.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
bot.tryEditMessage(inlineReceive.Message, fmt.Sprintf("%s\n\nPay this invoice:\n```%s```", inlineReceive.MessageText, invoice.PaymentRequest))
}
invoice.InvoiceMessage = msg
runtime.IgnoreError(bot.Bunt.Set(invoice))
log.Printf("[/invoice] Incvoice created. User: %s, amount: %d sat.", GetUserStr(inlineReceive.To.Telegram), inlineReceive.Amount)
}
func (bot *TipBot) inlineReceiveEvent(invoiceEvent *InvoiceEvent) {
bot.tryDeleteMessage(invoiceEvent.InvoiceMessage)
bot.notifyInvoiceReceivedEvent(invoiceEvent)
bot.finishInlineReceiveHandler(nil, &tb.Callback{Data: string(invoiceEvent.CallbackData)})
}
func (bot *TipBot) finishInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
// immediatelly set intransaction to block duplicate calls
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
rn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[getInlineReceive] %s", err.Error())
return
}
inlineReceive := rn.(*InlineReceive)
from := inlineReceive.From
to := inlineReceive.To
toUserStrMd := GetUserStrMd(to.Telegram)
fromUserStrMd := GetUserStrMd(from.Telegram)
toUserStr := GetUserStr(to.Telegram)
inlineReceive.MessageText = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendUpdateMessageAccept"), inlineReceive.Amount, fromUserStrMd, toUserStrMd))
memo := inlineReceive.Memo
if len(memo) > 0 {
inlineReceive.Message = inlineReceive.Message + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveAppendMemo"), memo)
inlineReceive.MessageText += fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveAppendMemo"), memo)
}
if !to.Initialized {
inlineReceive.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
inlineReceive.MessageText += "\n\n" + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
}
bot.tryEditMessage(c.Message, inlineReceive.Message, &tb.ReplyMarkup{})
bot.tryEditMessage(inlineReceive.Message, inlineReceive.MessageText, &tb.ReplyMarkup{})
// notify users
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, inlineReceive.Amount))
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), inlineReceive.Amount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[acceptInlineReceiveHandler] Error: Receive message to %s: %s", toUserStr, err)
log.Errorln(errmsg)
return
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)
@@ -205,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
+81 -36
View File
@@ -3,14 +3,21 @@ package telegram
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 (
@@ -20,13 +27,14 @@ var (
)
type InlineSend struct {
*transaction.Base
Message string `json:"inline_send_message"`
Amount int `json:"inline_send_amount"`
From *lnbits.User `json:"inline_send_from"`
To *tb.User `json:"inline_send_to"`
Memo string `json:"inline_send_memo"`
LanguageCode string `json:"languagecode"`
*storage.Base
Message string `json:"inline_send_message"`
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"`
Memo string `json:"inline_send_memo"`
LanguageCode string `json:"languagecode"`
}
func (bot TipBot) makeSendKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
@@ -57,7 +65,7 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
}
fromUser := LoadUser(ctx)
fromUserStr := GetUserStr(&q.From)
balance, err := bot.GetUserBalance(fromUser)
balance, err := bot.GetUserBalanceCached(fromUser)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
log.Errorln(errmsg)
@@ -69,14 +77,44 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
return
}
// check whether the 3rd argument is a username
// command is "@LightningTipBot send 123 @to_user This is the memo"
memo_argn := 2 // argument index at which the memo starts, will be 3 if there is a to_username in command
toUserDb := &lnbits.User{}
to_SpecificUser := false
if len(strings.Split(q.Text, " ")) > 2 {
to_username := strings.Split(q.Text, " ")[2]
if strings.HasPrefix(to_username, "@") {
toUserDb, err = GetUserByTelegramUsername(to_username[1:], bot) // must be without the @
if err != nil {
//bot.tryDeleteMessage(m)
//bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), toUserStrMention))
bot.inlineQueryReplyWithError(q,
fmt.Sprintf(TranslateUser(ctx, "sendUserHasNoWalletMessage"), to_username),
fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"),
bot.Telegram.Me.Username))
return
}
memo_argn = 3 // assume that memo starts after the to_username
to_SpecificUser = true
}
}
// check for memo in command
memo := GetMemoFromCommand(q.Text, 2)
memo := GetMemoFromCommand(q.Text, memo_argn)
urls := []string{
queryImage,
}
results := make(tb.Results, len(urls)) // []tb.Result
for i, url := range urls {
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineSendMessage"), fromUserStr, amount)
// modify message if payment is to specific user
if to_SpecificUser {
inlineMessage = fmt.Sprintf("@%s: %s", toUserDb.Telegram.Username, inlineMessage)
}
if len(memo) > 0 {
inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineSendAppendMemo"), memo)
}
@@ -96,16 +134,18 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
// add data to persistent object
inlineSend := InlineSend{
Base: transaction.New(transaction.ID(id)),
Message: inlineMessage,
From: fromUser,
Memo: memo,
Amount: amount,
LanguageCode: ctx.Value("publicLanguageCode").(string),
Base: storage.New(storage.ID(id)),
Message: inlineMessage,
From: fromUser,
To: toUserDb,
To_SpecificUser: to_SpecificUser,
Memo: memo,
Amount: amount,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
// 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{
@@ -120,32 +160,37 @@ 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
inlineSend.To = to.Telegram
// check if this payment goes to a specific user
if inlineSend.To_SpecificUser {
if inlineSend.To.Telegram.ID != to.Telegram.ID {
// log.Infof("User %d is not User %d", inlineSend.To.Telegram.ID, to.Telegram.ID)
return
}
} else {
// otherwise, we just set it to the user who has clicked
inlineSend.To = to
}
if fromUser.Telegram.ID == to.Telegram.ID {
bot.trySendMessage(fromUser.Telegram, Translate(ctx, "sendYourselfMessage"))
@@ -177,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
@@ -199,17 +244,18 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
_, err = bot.Telegram.Send(fromUser.Telegram, fmt.Sprintf(i18n.Translate(fromUser.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[sendInline] Error: Send message to %s: %s", toUserStr, err)
log.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)
@@ -217,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
+351
View File
@@ -0,0 +1,351 @@
package telegram
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/runtime"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
var (
inlineTipjarMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: false}
btnCancelInlineTipjar = inlineTipjarMenu.Data("🚫", "cancel_tipjar_inline")
btnAcceptInlineTipjar = inlineTipjarMenu.Data("💸 Pay", "confirm_tipjar_inline")
)
type InlineTipjar struct {
*storage.Base
Message string `json:"inline_tipjar_message"`
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"`
NTotal int `json:"inline_tipjar_ntotal"`
NGiven int `json:"inline_tipjar_ngiven"`
LanguageCode string `json:"languagecode"`
}
func (bot TipBot) mapTipjarLanguage(ctx context.Context, command string) context.Context {
if len(strings.Split(command, " ")) > 1 {
c := strings.Split(command, " ")[0][1:] // cut the /
ctx = bot.commandTranslationMap(ctx, c)
}
return ctx
}
func (bot TipBot) createTipjar(ctx context.Context, text string, sender *tb.User) (*InlineTipjar, error) {
amount, err := decodeAmountFromCommand(text)
if err != nil {
return nil, errors.New(errors.DecodeAmountError, err)
}
peruserStr, err := getArgumentFromCommand(text, 2)
if err != nil {
return nil, errors.New(errors.DecodePerUserAmountError, err)
}
perUserAmount, err := getAmount(peruserStr)
if err != nil {
return nil, errors.New(errors.InvalidAmountError, err)
}
if perUserAmount < 1 || amount%perUserAmount != 0 {
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("invalid amount per user"))
}
nTotal := int(amount / perUserAmount)
toUser := LoadUser(ctx)
// toUserStr := GetUserStr(sender)
// // check for memo in command
memo := GetMemoFromCommand(text, 3)
inlineMessage := fmt.Sprintf(
Translate(ctx, "inlineTipjarMessage"),
perUserAmount,
GetUserStrMd(toUser.Telegram),
0,
amount,
0,
MakeTipjarbar(0, amount),
)
if len(memo) > 0 {
inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineTipjarAppendMemo"), memo)
}
id := fmt.Sprintf("inl-tipjar-%d-%d-%s", sender.ID, amount, RandStringRunes(5))
return &InlineTipjar{
Base: storage.New(storage.ID(id)),
Message: inlineMessage,
Amount: amount,
To: toUser,
Memo: memo,
PerUserAmount: perUserAmount,
NTotal: nTotal,
NGiven: 0,
GivenAmount: 0,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}, nil
}
func (bot TipBot) makeTipjar(ctx context.Context, m *tb.Message, query bool) (*InlineTipjar, error) {
tipjar, err := bot.createTipjar(ctx, m.Text, m.Sender)
if err != nil {
switch err.(errors.TipBotError).Code {
case errors.DecodeAmountError:
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineTipjarHelpText"), Translate(ctx, "inlineTipjarInvalidAmountMessage")))
bot.tryDeleteMessage(m)
return nil, err
case errors.DecodePerUserAmountError:
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineTipjarHelpText"), ""))
bot.tryDeleteMessage(m)
return nil, err
case errors.InvalidAmountError:
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineTipjarHelpText"), Translate(ctx, "inlineTipjarInvalidAmountMessage")))
bot.tryDeleteMessage(m)
return nil, err
case errors.InvalidAmountPerUserError:
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineTipjarHelpText"), Translate(ctx, "inlineTipjarInvalidPeruserAmountMessage")))
bot.tryDeleteMessage(m)
return nil, err
case errors.GetBalanceError:
// log.Errorln(err.Error())
bot.tryDeleteMessage(m)
return nil, err
case errors.BalanceToLowError:
// log.Errorf(err.Error())
bot.trySendMessage(m.Sender, Translate(ctx, "inlineSendBalanceLowMessage"))
bot.tryDeleteMessage(m)
return nil, err
}
}
return tipjar, err
}
func (bot TipBot) makeQueryTipjar(ctx context.Context, q *tb.Query, query bool) (*InlineTipjar, error) {
tipjar, err := bot.createTipjar(ctx, q.Text, &q.From)
if err != nil {
switch err.(errors.TipBotError).Code {
case errors.DecodeAmountError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.DecodePerUserAmountError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.InvalidAmountError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.InvalidAmountPerUserError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineTipjarInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.GetBalanceError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.BalanceToLowError:
log.Errorf(err.Error())
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
return nil, err
}
}
return tipjar, err
}
func (bot TipBot) makeTipjarKeyboard(ctx context.Context, inlineTipjar *InlineTipjar) *tb.ReplyMarkup {
// inlineTipjarMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
// slice of buttons
buttons := make([]tb.Btn, 0)
cancelInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_tipjar_inline", inlineTipjar.ID)
buttons = append(buttons, cancelInlineTipjarButton)
acceptInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "payReceiveButtonMessage"), "confirm_tipjar_inline", inlineTipjar.ID)
buttons = append(buttons, acceptInlineTipjarButton)
inlineTipjarMenu.Inline(
inlineTipjarMenu.Row(buttons...))
return inlineTipjarMenu
}
func (bot TipBot) tipjarHandler(ctx context.Context, m *tb.Message) {
bot.anyTextHandler(ctx, m)
if m.Private() {
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineTipjarHelpText"), Translate(ctx, "inlineTipjarHelpTipjarInGroup")))
return
}
ctx = bot.mapTipjarLanguage(ctx, m.Text)
inlineTipjar, err := bot.makeTipjar(ctx, m, false)
if err != nil {
log.Errorf("[tipjar] %s", err.Error())
return
}
toUserStr := GetUserStr(m.Sender)
bot.trySendMessage(m.Chat, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
log.Infof("[tipjar] %s created tipjar %s: %d sat (%d per user)", toUserStr, inlineTipjar.ID, inlineTipjar.Amount, inlineTipjar.PerUserAmount)
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
}
func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) {
inlineTipjar, err := bot.makeQueryTipjar(ctx, q, false)
if err != nil {
// log.Errorf("[tipjar] %s", err.Error())
return
}
urls := []string{
queryImage,
}
results := make(tb.Results, len(urls)) // []tb.Result
for i, url := range urls {
result := &tb.ArticleResult{
// URL: url,
Text: inlineTipjar.Message,
Title: fmt.Sprintf(TranslateUser(ctx, "inlineResultTipjarTitle"), inlineTipjar.Amount),
Description: TranslateUser(ctx, "inlineResultTipjarDescription"),
// required for photos
ThumbURL: url,
}
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeTipjarKeyboard(ctx, inlineTipjar).InlineKeyboard}
results[i] = result
// needed to set a unique string ID for each result
results[i].SetResultID(inlineTipjar.ID)
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)
}
err = bot.Telegram.Answer(q, &tb.QueryResponse{
Results: results,
CacheTime: 1,
IsPersonal: true,
})
if err != nil {
log.Errorln(err)
}
}
func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback) {
from := LoadUser(ctx)
if from.Wallet == nil {
return
}
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.Error())
return
}
inlineTipjar := fn.(*InlineTipjar)
to := inlineTipjar.To
if !inlineTipjar.Active {
log.Errorf(fmt.Sprintf("[tipjar] tipjar %s inactive.", inlineTipjar.ID))
return
}
if from.Telegram.ID == to.Telegram.ID {
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
return
}
// // check if to user has already given to the tipjar
for _, a := range inlineTipjar.From {
if a.Telegram.ID == from.Telegram.ID {
// to user is already in To slice, has taken from facuet
// log.Infof("[tipjar] %s already gave to tipjar %s", GetUserStr(to.Telegram), inlineTipjar.ID)
return
}
}
if inlineTipjar.GivenAmount < inlineTipjar.Amount {
toUserStrMd := GetUserStrMd(to.Telegram)
fromUserStrMd := GetUserStrMd(from.Telegram)
toUserStr := GetUserStr(to.Telegram)
fromUserStr := GetUserStr(from.Telegram)
// todo: user new get username function to get userStrings
transactionMemo := fmt.Sprintf("Tipjar from %s to %s (%d sat).", fromUserStr, toUserStr, inlineTipjar.PerUserAmount)
t := NewTransaction(bot, from, to, inlineTipjar.PerUserAmount, TransactionType("tipjar"))
t.Memo = transactionMemo
success, err := t.Send()
if !success {
bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
errMsg := fmt.Sprintf("[tipjar] Transaction failed: %s", err.Error())
log.Errorln(errMsg)
return
}
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))
if err != nil {
errmsg := fmt.Errorf("[tipjar] Error: Send message to %s: %s", toUserStr, err)
log.Warnln(errmsg)
}
// build tipjar message
inlineTipjar.Message = fmt.Sprintf(
i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarMessage"),
inlineTipjar.PerUserAmount,
GetUserStrMd(inlineTipjar.To.Telegram),
inlineTipjar.GivenAmount,
inlineTipjar.Amount,
inlineTipjar.NGiven,
MakeTipjarbar(inlineTipjar.GivenAmount, inlineTipjar.Amount),
)
memo := inlineTipjar.Memo
if len(memo) > 0 {
inlineTipjar.Message = inlineTipjar.Message + fmt.Sprintf(i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarAppendMemo"), memo)
}
// if inlineTipjar.UserNeedsWallet {
// inlineTipjar.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
// }
// update message
log.Infoln(inlineTipjar.Message)
bot.tryEditMessage(c.Message, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
}
if inlineTipjar.GivenAmount >= inlineTipjar.Amount {
// tipjar is full
inlineTipjar.Message = fmt.Sprintf(
i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarEndedMessage"),
GetUserStrMd(inlineTipjar.To.Telegram),
inlineTipjar.Amount,
inlineTipjar.NGiven,
)
// if inlineTipjar.UserNeedsWallet {
// inlineTipjar.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
// }
bot.tryEditMessage(c.Message, inlineTipjar.Message)
inlineTipjar.Active = false
}
}
func (bot *TipBot) cancelInlineTipjarHandler(ctx context.Context, c *tb.Callback) {
tx := &InlineTipjar{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[cancelInlineTipjarHandler] %s", err.Error())
return
}
inlineTipjar := fn.(*InlineTipjar)
if c.Sender.ID == inlineTipjar.To.Telegram.ID {
bot.tryEditMessage(c.Message, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
// set the inlineTipjar inactive
inlineTipjar.Active = false
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
+89 -17
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
}
@@ -122,7 +190,11 @@ func (bot TipBot) logMessageInterceptor(ctx context.Context, i interface{}) (con
case *tb.Message:
m := i.(*tb.Message)
if m.Text != "" {
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
log_string := fmt.Sprintf("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
if m.IsReply() {
log_string = fmt.Sprintf("%s -> %s", log_string, GetUserStr(m.ReplyTo.Sender))
}
log.Infof(log_string)
} else if m.Photo != nil {
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, photoTag)
}
+127 -34
View File
@@ -4,16 +4,61 @@ import (
"bytes"
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"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))
@@ -22,32 +67,24 @@ 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)
if m.Chat.Type != tb.ChatPrivate {
// delete message
NewMessage(m, WithDuration(0, bot.Telegram))
return
}
if len(strings.Split(m.Text, " ")) < 2 {
bot.trySendMessage(m.Sender, helpInvoiceUsage(ctx, Translate(ctx, "invoiceEnterAmountMessage")))
return
}
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
userStr := GetUserStr(m.Sender)
amount, err := decodeAmountFromCommand(m.Text)
if err != nil {
userStr := GetUserStr(user.Telegram)
if m.Chat.Type != tb.ChatPrivate {
// delete message
bot.tryDeleteMessage(m)
return
}
if amount > 0 {
} else {
bot.trySendMessage(m.Sender, helpInvoiceUsage(ctx, Translate(ctx, "invoiceValidAmountMessage")))
// if no amount is in the command, ask for it
amount, err := decodeAmountFromCommand(m.Text)
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
// // no amount was entered, set user state and ask fo""r amount
bot.askForAmount(ctx, "", "CreateInvoiceState", 0, 0, m.Text)
return
}
@@ -63,8 +100,35 @@ func (bot TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
memo = memo + tag
}
creatingMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
log.Infof("[/invoice] Creating invoice for %s of %d sat.", userStr, amount)
// generate invoice
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, InvoiceCallbackGeneric, "")
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
log.Errorln(errmsg)
return
}
// create qr code
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
log.Errorln(errmsg)
return
}
// 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,
@@ -73,21 +137,50 @@ func (bot TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
Webhook: internal.Configuration.Lnbits.WebhookServer},
bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err)
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
log.Errorln(errmsg)
return
return InvoiceEvent{}, err
}
invoiceEvent := InvoiceEvent{
Invoice: &Invoice{PaymentHash: invoice.PaymentHash,
PaymentRequest: invoice.PaymentRequest,
Amount: amount,
Memo: memo},
User: user,
Callback: callback,
CallbackData: callbackData,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
// save invoice struct for later use
runtime.IgnoreError(bot.Bunt.Set(invoiceEvent))
return invoiceEvent, nil
}
// create qr code
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err)
log.Errorln(errmsg)
return
func (bot *TipBot) notifyInvoiceReceivedEvent(invoiceEvent *InvoiceEvent) {
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
}
type LNURLInvoice struct {
*Invoice
Comment string `json:"comment"`
User *lnbits.User `json:"user"`
CreatedAt time.Time `json:"created_at"`
Paid bool `json:"paid"`
PaidAt time.Time `json:"paid_at"`
}
func (lnurlInvoice LNURLInvoice) Key() string {
return fmt.Sprintf("lnurl-p:%s", lnurlInvoice.PaymentHash)
}
func (bot *TipBot) lnurlReceiveEvent(invoiceEvent *InvoiceEvent) {
bot.notifyInvoiceReceivedEvent(invoiceEvent)
tx := &LNURLInvoice{Invoice: &Invoice{PaymentHash: invoiceEvent.PaymentHash}}
err := bot.Bunt.Get(tx)
log.Debugf("[lnurl-p] Received invoice for %s of %d sat.", GetUserStr(invoiceEvent.User.Telegram), tx.Amount)
if err == nil {
if len(tx.Comment) > 0 {
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf(`✉️ %s`, str.MarkdownEscape(tx.Comment)))
}
}
// 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
}
+23 -6
View File
@@ -4,14 +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
@@ -21,22 +24,36 @@ func (bot TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
// reply only in private message
if m.Chat.Type != tb.ChatPrivate {
// delete message
NewMessage(m, WithDuration(0, bot.Telegram))
bot.tryDeleteMessage(m)
}
// first check whether the user is initialized
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))
}
+237
View File
@@ -0,0 +1,237 @@
package telegram
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"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"
lnurl "github.com/fiatjaf/go-lnurl"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
// LnurlPayState saves the state of the user for an LNURL payment
type LnurlPayState struct {
*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
// at this point, the user hans't necessarily entered an amount yet
func (bot *TipBot) lnurlPayHandler(ctx context.Context, m *tb.Message, payParams LnurlPayState) {
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
// object that holds all information about the send payment
id := fmt.Sprintf("lnurlp-%d-%s", m.Sender.ID, RandStringRunes(5))
lnurlPayState := &LnurlPayState{
Base: storage.New(storage.ID(id)),
From: user,
LNURLPayParams: payParams.LNURLPayParams,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
// first we check whether an amount is present in the command
amount, amount_err := decodeAmountFromCommand(m.Text)
// 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 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.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
// add result to persistent struct
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
// now we actualy check whether the amount was in the command and if not, ask for it
if 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())
// bot.trySendMessage(m.Sender, err.Error())
return
}
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
// directly go to confirm
bot.lnurlPayHandlerSend(ctx, m)
return
}
// lnurlPayHandlerSend is invoked when the user has delivered an amount and is ready to pay
func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
// assert that user has entered an amount
if user.StateKey != lnbits.UserHasEnteredAmount {
log.Errorln("[lnurlPayHandlerSend] 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("[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: storage.New(storage.ID(enterAmountData.ID))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
lnurlPayState := fn.(*LnurlPayState)
// LnurlPayState loaded
client, err := bot.GetHttpClient()
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
qs := callbackUrl.Query()
// add amount to query string
qs.Set("amount", strconv.FormatInt(lnurlPayState.Amount, 10)) // msat
// add comment to query string
if len(lnurlPayState.Comment) > 0 {
qs.Set("comment", lnurlPayState.Comment)
}
callbackUrl.RawQuery = qs.Encode()
res, err := client.Get(callbackUrl.String())
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", 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.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
}
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 LNURLPayValues: %s", error_reason)
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
return
}
lnurlPayState.LNURLPayValues = response2
// add result to persistent struct
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
bot.Telegram.Delete(statusMsg)
m.Text = fmt.Sprintf("/pay %s", response2.PR)
bot.payHandler(ctx, m)
}
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")
}
host := strings.ToLower(split[1])
name := strings.ToLower(split[0])
// convert address scheme into LNURL Bech32 format
callback := fmt.Sprintf("https://%s/.well-known/lnurlp/%s", host, name)
log.Infof("[sendToLightningAddress] %s: callback: %s", GetUserStr(m.Sender), callback)
lnurl, err := lnurl.LNURLEncode(callback)
if err != nil {
return err
}
if amount > 0 {
// only when amount is given, we will also add a comment to the command
// we do this because if the amount is not given, we will have to ask for it later
// in the lnurl handler and we don't want to add another step where we ask for a comment
// the command to pay to lnurl with comment is /lnurl <amount> <lnurl> <comment>
// check if comment is presentin lnrul-p
memo := GetMemoFromCommand(m.Text, 3)
m.Text = fmt.Sprintf("/lnurl %d %s", amount, lnurl)
// shorten comment to allowed length
if len(memo) > 0 {
m.Text = m.Text + " " + memo
}
} else {
// no amount was given so we will just send the lnurl
// this will invoke the "enter amount" dialog in the lnurl handler
m.Text = fmt.Sprintf("/lnurl %s", lnurl)
}
bot.lnurlHandler(ctx, m)
return nil
}
+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)
}
+160 -313
View File
@@ -3,280 +3,24 @@ package telegram
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"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"
)
// lnurlHandler is invoked on /lnurl command
func (bot TipBot) lnurlHandler(ctx context.Context, m *tb.Message) {
// commands:
// /lnurl
// /lnurl <LNURL>
// or /lnurl <amount> <LNURL>
log.Infof("[lnurlHandler] %s", m.Text)
// if only /lnurl is entered, show the lnurl of the user
if m.Text == "/lnurl" {
bot.lnurlReceiveHandler(ctx, m)
return
}
// assume payment
// HandleLNURL by fiatjaf/go-lnurl
msg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlResolvingUrlMessage"))
_, params, err := HandleLNURL(m.Text)
if err != nil {
bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), "could not resolve LNURL."))
log.Errorln(err)
return
}
var payParams LnurlStateResponse
switch params.(type) {
case lnurl.LNURLPayResponse1:
payParams = LnurlStateResponse{LNURLPayResponse1: params.(lnurl.LNURLPayResponse1)}
log.Infof("[lnurlHandler] %s", payParams.Callback)
default:
err := fmt.Errorf("invalid LNURL type.")
log.Errorln(err)
bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
// bot.trySendMessage(m.Sender, err.Error())
return
}
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
// if no amount is in the command, ask for it
amount, err := decodeAmountFromCommand(m.Text)
if err != nil || amount < 1 {
// set LNURLPayResponse1 in the state of the user
paramsJson, err := json.Marshal(payParams)
if err != nil {
log.Errorln(err)
return
}
SetUserState(user, bot, lnbits.UserStateLNURLEnterAmount, string(paramsJson))
bot.tryDeleteMessage(msg)
// Let the user enter an amount and return
bot.trySendMessage(m.Sender,
fmt.Sprintf(Translate(ctx, "lnurlEnterAmountMessage"), payParams.MinSendable/1000, payParams.MaxSendable/1000),
tb.ForceReply)
} else {
// amount is already present in the command
// amount not in allowed range from LNURL
// if int64(amount) > (payParams.MaxSendable/1000) || int64(amount) < (payParams.MinSendable/1000) {
// err = fmt.Errorf("amount not in range")
// log.Errorln(err)
// bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), payParams.MinSendable/1000, payParams.MaxSendable/1000))
// ResetUserState(user, bot)
// return
// }
// set also amount in the state of the user
payParams.Amount = amount
// check if comment is presentin lnrul-p
memo := GetMemoFromCommand(m.Text, 3)
// shorten comment to allowed length
if len(memo) > int(payParams.CommentAllowed) {
memo = memo[:payParams.CommentAllowed]
}
// save it
payParams.Comment = memo
paramsJson, err := json.Marshal(payParams)
if err != nil {
log.Errorln(err)
// bot.trySendMessage(m.Sender, err.Error())
return
}
SetUserState(user, bot, lnbits.UserStateConfirmLNURLPay, string(paramsJson))
bot.tryDeleteMessage(msg)
// directly go to confirm
bot.lnurlPayHandler(ctx, m)
}
}
func (bot *TipBot) UserGetLightningAddress(user *tb.User) (string, error) {
if len(user.Username) > 0 {
return fmt.Sprintf("%s@%s", strings.ToLower(user.Username), strings.ToLower(internal.Configuration.Bot.LNURLHostUrl.Hostname())), nil
} else {
return "", fmt.Errorf("user has no username")
}
}
func UserGetLNURL(user *tb.User) (string, error) {
name := strings.ToLower(strings.ToLower(user.Username))
if len(name) == 0 {
return "", fmt.Errorf("user has no username.")
}
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, name)
log.Debugf("[lnurlReceiveHandler] %s's LNURL: %s", GetUserStr(user), callback)
lnurlEncode, err := lnurl.LNURLEncode(callback)
if err != nil {
return "", err
}
return lnurlEncode, nil
}
// lnurlReceiveHandler outputs the LNURL of the user
func (bot TipBot) lnurlReceiveHandler(ctx context.Context, m *tb.Message) {
lnurlEncode, err := UserGetLNURL(m.Sender)
if err != nil {
errmsg := fmt.Sprintf("[lnurlReceiveHandler] Failed to get LNURL: %s", err)
log.Errorln(errmsg)
bot.Telegram.Send(m.Sender, Translate(ctx, "lnurlNoUsernameMessage"))
}
// create qr code
qr, err := qrcode.Encode(lnurlEncode, qrcode.Medium, 256)
if err != nil {
errmsg := fmt.Sprintf("[lnurlReceiveHandler] Failed to create QR code for LNURL: %s", err)
log.Errorln(errmsg)
return
}
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlReceiveInfoText"))
// send the lnurl data to user
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 {
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 LnurlStateResponse
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.MaxSendable/1000) || amount < (stateResponse.MinSendable/1000) {
err = fmt.Errorf("amount not in range")
log.Errorln(err)
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), stateResponse.MinSendable/1000, stateResponse.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 {
bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), "could not receive invoice (wrong address?)."))
return
}
bot.Telegram.Delete(msg)
c.Text = fmt.Sprintf("/pay %s", response2.PR)
bot.payHandler(ctx, c)
}
}
func getHttpClient() (*http.Client, error) {
func (bot *TipBot) GetHttpClient() (*http.Client, error) {
client := http.Client{}
if internal.Configuration.Bot.HttpProxy != "" {
proxyUrl, err := url.Parse(internal.Configuration.Bot.HttpProxy)
@@ -289,11 +33,133 @@ func getHttpClient() (*http.Client, error) {
return &client, nil
}
func (bot TipBot) cancelLnUrlHandler(c *tb.Callback) {
}
// from https://github.com/fiatjaf/go-lnurl
func HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
// lnurlHandler is invoked on /lnurl command
func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) {
// commands:
// /lnurl
// /lnurl <LNURL>
// or /lnurl <amount> <LNURL>
if m.Chat.Type != tb.ChatPrivate {
return
}
log.Infof("[lnurlHandler] %s", m.Text)
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
// if only /lnurl is entered, show the lnurl of the user
if m.Text == "/lnurl" {
bot.lnurlReceiveHandler(ctx, m)
return
}
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlResolvingUrlMessage"))
var lnurlSplit string
split := strings.Split(m.Text, " ")
if _, err := decodeAmountFromCommand(m.Text); err == nil {
// command is /lnurl 123 <LNURL> [memo]
if len(split) > 2 {
lnurlSplit = split[2]
}
} else if len(split) > 1 {
lnurlSplit = split[1]
} else {
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "Could not parse command."))
log.Warnln("[/lnurl] Could not parse command.")
return
}
// 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, "errorReasonMessage"), err.Error()))
log.Warnf("[HandleLNURL] Error: %s", err.Error())
return
}
switch params.(type) {
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)
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:
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
}
}
func (bot *TipBot) UserGetLightningAddress(user *lnbits.User) (string, error) {
if len(user.Telegram.Username) > 0 {
return fmt.Sprintf("%s@%s", strings.ToLower(user.Telegram.Username), strings.ToLower(internal.Configuration.Bot.LNURLHostUrl.Hostname())), nil
} else {
lnaddr, err := bot.UserGetAnonLightningAddress(user)
return lnaddr, err
}
}
func (bot *TipBot) UserGetAnonLightningAddress(user *lnbits.User) (string, error) {
return fmt.Sprintf("%s@%s", fmt.Sprint(user.AnonID), strings.ToLower(internal.Configuration.Bot.LNURLHostUrl.Hostname())), nil
}
func UserGetLNURL(user *lnbits.User) (string, error) {
// before: we used the username for the LNURL
// name := strings.ToLower(strings.ToLower(user.Telegram.Username))
// if len(name) == 0 {
// name = fmt.Sprint(user.AnonID)
// // return "", fmt.Errorf("user has no username.")
// }
// now: use only the anon ID as LNURL
name := fmt.Sprint(user.AnonID)
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, name)
log.Debugf("[lnurlReceiveHandler] %s's LNURL: %s", GetUserStr(user.Telegram), callback)
lnurlEncode, err := lnurl.LNURLEncode(callback)
if err != nil {
return "", err
}
return lnurlEncode, nil
}
// lnurlReceiveHandler outputs the LNURL of the user
func (bot TipBot) lnurlReceiveHandler(ctx context.Context, m *tb.Message) {
fromUser := LoadUser(ctx)
lnurlEncode, err := UserGetLNURL(fromUser)
if err != nil {
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to get LNURL: %s", err.Error())
log.Errorln(errmsg)
bot.Telegram.Send(m.Sender, Translate(ctx, "lnurlNoUsernameMessage"))
}
// create qr code
qr, err := qrcode.Encode(lnurlEncode, qrcode.Medium, 256)
if err != nil {
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to create QR code for LNURL: %s", err.Error())
log.Errorln(errmsg)
return
}
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlReceiveInfoText"))
// send the lnurl data to user
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lnurlEncode)})
}
// fiatjaf/go-lnurl 1.8.4 with proxy
func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
var err error
var rawurl string
@@ -307,13 +173,24 @@ func HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
}
} 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
}
@@ -335,15 +212,24 @@ func HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
return rawurl, value, nil
}
}
client, err := getHttpClient()
// // 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
}
resp, err := client.Get(rawurl)
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 {
@@ -361,54 +247,15 @@ func HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
switch j.Get("tag").String() {
case "withdrawRequest":
value, err := lnurl.HandleWithdraw(j)
value, err := lnurl.HandleWithdraw(b)
return rawurl, value, err
case "payRequest":
value, err := lnurl.HandlePay(j)
return rawurl, value, err
case "channelRequest":
value, err := lnurl.HandleChannel(j)
value, err := lnurl.HandlePay(b)
return rawurl, value, err
// case "channelRequest":
// 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.")
}
}
func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, address string, amount int) error {
split := strings.Split(address, "@")
if len(split) != 2 {
return fmt.Errorf("lightning address format wrong")
}
host := strings.ToLower(split[1])
name := strings.ToLower(split[0])
// convert address scheme into LNURL Bech32 format
callback := fmt.Sprintf("https://%s/.well-known/lnurlp/%s", host, name)
log.Infof("[sendToLightningAddress] %s: callback: %s", GetUserStr(m.Sender), callback)
lnurl, err := lnurl.LNURLEncode(callback)
if err != nil {
return err
}
if amount > 0 {
// only when amount is given, we will also add a comment to the command
// we do this because if the amount is not given, we will have to ask for it later
// in the lnurl handler and we don't want to add another step where we ask for a comment
// the command to pay to lnurl with comment is /lnurl <amount> <lnurl> <comment>
// check if comment is presentin lnrul-p
memo := GetMemoFromCommand(m.Text, 3)
m.Text = fmt.Sprintf("/lnurl %d %s", amount, lnurl)
// shorten comment to allowed length
if len(memo) > 0 {
m.Text = m.Text + " " + memo
}
} else {
// no amount was given so we will just send the lnurl
// this will invoke the "enter amount" dialog in the lnurl handler
m.Text = fmt.Sprintf("/lnurl %s", lnurl)
}
bot.lnurlHandler(ctx, m)
return nil
}
+5 -11
View File
@@ -4,9 +4,7 @@ import (
"strconv"
"time"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type Message struct {
@@ -16,10 +14,10 @@ type Message struct {
type MessageOption func(m *Message)
func WithDuration(duration time.Duration, bot *tb.Bot) MessageOption {
func WithDuration(duration time.Duration, tipBot *TipBot) MessageOption {
return func(m *Message) {
m.duration = duration
go m.dispose(bot)
go m.dispose(tipBot)
}
}
@@ -37,17 +35,13 @@ func (msg Message) Key() string {
return strconv.Itoa(msg.Message.ID)
}
func (msg Message) dispose(telegram *tb.Bot) {
func (msg Message) dispose(tipBot *TipBot) {
// do not delete messages from private chat
if msg.Message.Private() {
return
}
go func() {
time.Sleep(msg.duration)
err := telegram.Delete(msg.Message)
if err != nil {
log.Println(err.Error())
return
}
tipBot.tryDeleteMessage(msg.Message)
}()
}
+77 -59
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,19 +33,20 @@ func helpPayInvoiceUsage(ctx context.Context, errormsg string) string {
}
type PayData struct {
*transaction.Base
From *lnbits.User `json:"from"`
Invoice string `json:"invoice"`
Hash string `json:"hash"`
Proof string `json:"proof"`
Memo string `json:"memo"`
Message string `json:"message"`
Amount int64 `json:"amount"`
LanguageCode string `json:"languagecode"`
*storage.Base
From *lnbits.User `json:"from"`
Invoice string `json:"invoice"`
Hash string `json:"hash"`
Proof string `json:"proof"`
Memo string `json:"memo"`
Message string `json:"message"`
Amount int64 `json:"amount"`
LanguageCode string `json:"languagecode"`
TelegramMessage *tb.Message `json:"telegrammessage"`
}
// payHandler invoked on "/pay lnbc..." command
func (bot TipBot) payHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
// check and print all commands
bot.anyTextHandler(ctx, m)
user := LoadUser(ctx)
@@ -50,16 +54,16 @@ func (bot TipBot) payHandler(ctx context.Context, m *tb.Message) {
return
}
if len(strings.Split(m.Text, " ")) < 2 {
NewMessage(m, WithDuration(0, bot.Telegram))
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, ""))
return
}
userStr := GetUserStr(m.Sender)
paymentRequest, err := getArgumentFromCommand(m.Text, 1)
if err != nil {
NewMessage(m, WithDuration(0, bot.Telegram))
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
}
@@ -71,29 +75,31 @@ 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"))
errmsg := fmt.Sprint("[/pay] Error: invoice without amount")
log.Errorln(errmsg)
log.Warnln(errmsg)
return
}
// check user balance first
balance, err := bot.GetUserBalance(user)
if err != nil {
NewMessage(m, WithDuration(0, bot.Telegram))
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err)
NewMessage(m, WithDuration(0, bot))
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err.Error())
log.Errorln(errmsg)
bot.trySendMessage(m.Sender, Translate(ctx, "errorTryLaterMessage"))
return
}
if amount > balance {
NewMessage(m, WithDuration(0, bot.Telegram))
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "insufficientFundsMessage"), balance, amount))
return
}
@@ -107,23 +113,10 @@ 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))
payData := PayData{
From: user,
Invoice: paymentRequest,
Base: transaction.New(transaction.ID(id)),
Amount: int64(amount),
Memo: bolt11.Description,
Message: confirmText,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
// add result to persistent struct
runtime.IgnoreError(payData.Set(payData, bot.Bunt))
SetUserState(user, bot, lnbits.UserStateConfirmPayment, paymentRequest)
// // // create inline buttons
payButton := paymentConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "confirm_pay")
@@ -136,16 +129,32 @@ func (bot TipBot) payHandler(ctx context.Context, m *tb.Message) {
payButton,
cancelButton),
)
bot.trySendMessage(m.Chat, confirmText, paymentConfirmationMenu)
payMessage := bot.trySendMessage(m.Chat, confirmText, paymentConfirmationMenu)
payData := &PayData{
Base: storage.New(storage.ID(id)),
From: user,
Invoice: paymentRequest,
Amount: int64(amount),
Memo: bolt11.Description,
Message: confirmText,
LanguageCode: ctx.Value("publicLanguageCode").(string),
TelegramMessage: payMessage,
}
// add result to persistent struct
runtime.IgnoreError(payData.Set(payData, bot.Bunt))
SetUserState(user, bot, lnbits.UserStateConfirmPayment, paymentRequest)
}
// confirmPayHandler when user clicked pay on payment confirmation
func (bot TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
tx := &PayData{Base: transaction.New(transaction.ID(c.Data))}
func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
tx := &PayData{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.Bunt)
// immediatelly set intransaction to block duplicate calls
if err != nil {
log.Errorf("[confirmPayHandler] %s", err)
log.Errorf("[confirmPayHandler] %s", err.Error())
return
}
payData := sn.(*PayData)
@@ -154,19 +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)
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{})
@@ -183,20 +186,34 @@ func (bot TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
ResetUserState(user, bot)
userStr := GetUserStr(c.Sender)
// update button text
bot.tryEditMessage(
c.Message,
payData.Message,
&tb.ReplyMarkup{
InlineKeyboard: [][]tb.InlineButton{
{tb.InlineButton{Text: i18n.Translate(payData.LanguageCode, "lnurlGettingUserMessage")}},
},
},
)
log.Infof("[/pay] Attempting %s's invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
// pay invoice
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoiceString}, bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of %s: %s", userStr, err)
if len(err.Error()) == 0 {
err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
}
// bot.trySendMessage(c.Sender, fmt.Sprintf(invoicePaymentFailedMessage, err))
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), str.MarkdownEscape(err.Error())), &tb.ReplyMarkup{})
err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
// verbose error message, turned off for now
// if len(err.Error()) == 0 {
// err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
// }
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), str.MarkdownEscape(err.Error())), &tb.ReplyMarkup{})
log.Errorln(errmsg)
return
}
payData.Hash = invoice.PaymentHash
payData.InTransaction = false
if c.Message.Private() {
// if the command was invoked in private chat
@@ -206,20 +223,22 @@ func (bot TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
bot.trySendMessage(c.Sender, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePublicPaidMessage"), userStr), &tb.ReplyMarkup{})
}
log.Printf("[pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
log.Infof("[⚡️ pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
return
}
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
func (bot TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) {
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)
log.Errorf("[cancelPaymentHandler] %s", err.Error())
return
}
payData := sn.(*PayData)
@@ -228,6 +247,5 @@ func (bot TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) {
return
}
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"), &tb.ReplyMarkup{})
payData.InTransaction = false
payData.Inactivate(payData, bot.Bunt)
}
+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
}
+62 -42
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"`
@@ -58,21 +61,21 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
}
// reset state immediately
ResetUserState(user, *bot)
ResetUserState(user, bot)
// check and print all commands
// If the send is a reply, then trigger /tip handler
if m.IsReply() {
if m.IsReply() && m.Chat.Type != tb.ChatPrivate {
bot.tipHandler(ctx, m)
return
}
if ok, errstr := bot.SendCheckSyntax(ctx, m); !ok {
bot.trySendMessage(m.Sender, helpSendUsage(ctx, errstr))
NewMessage(m, WithDuration(0, bot.Telegram))
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,15 +101,26 @@ 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)
return
}
// ASSUME INTERNAL SEND TO TELEGRAM USER
if err != nil || amount < 1 {
errmsg := fmt.Sprintf("[/send] Error: Send amount not valid.")
log.Errorln(errmsg)
log.Warnln(errmsg)
// immediately delete if the amount is bullshit
NewMessage(m, WithDuration(0, bot.Telegram))
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, helpSendUsage(ctx, Translate(ctx, "sendValidAmountMessage")))
return
}
@@ -118,7 +132,7 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
toUserStrMention := ""
toUserStrWithoutAt := ""
// check for user in command, accepts user mention or plan username without @
// check for user in command, accepts user mention or plain username without @
if len(m.Entities) > 1 && m.Entities[1].Type == "mention" {
toUserStrMention = m.Text[m.Entities[1].Offset : m.Entities[1].Offset+m.Entities[1].Length]
toUserStrWithoutAt = strings.TrimPrefix(toUserStrMention, "@")
@@ -128,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)
@@ -139,8 +153,17 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
toUserDb, err := GetUserByTelegramUsername(toUserStrWithoutAt, *bot)
if err != nil {
NewMessage(m, WithDuration(0, bot.Telegram))
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), toUserStrMention))
NewMessage(m, WithDuration(0, bot))
// 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
}
@@ -151,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,
@@ -166,14 +189,14 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
sendDataJson, err := json.Marshal(sendData)
if err != nil {
NewMessage(m, WithDuration(0, bot.Telegram))
NewMessage(m, WithDuration(0, bot))
log.Printf("[/send] Error: %s\n", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprint(Translate(ctx, "errorTryLaterMessage")))
return
}
// save the send data to the Database
// log.Debug(sendData)
SetUserState(user, *bot, lnbits.UserStateConfirmSend, string(sendDataJson))
SetUserState(user, bot, lnbits.UserStateConfirmSend, string(sendDataJson))
sendButton := sendConfirmationMenu.Data(Translate(ctx, "sendButtonMessage"), "confirm_send")
cancelButton := sendConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_send")
sendButton.Data = id
@@ -193,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)
@@ -204,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{})
@@ -224,7 +242,7 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
// decode callback data
// log.Debug("[send] Callback: %s", c.Data)
from := LoadUser(ctx)
ResetUserState(from, *bot) // we don't need to check the statekey anymore like we did earlier
ResetUserState(from, bot) // we don't need to check the statekey anymore like we did earlier
// information about the send
toId := sendData.ToTelegramId
@@ -245,20 +263,20 @@ 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))
@@ -283,13 +301,16 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
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))}
ResetUserState(user, bot)
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 {
@@ -297,6 +318,5 @@ func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) {
}
// remove buttons from confirmation message
bot.tryEditMessage(c.Message, i18n.Translate(sendData.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
sendData.InTransaction = false
sendData.Inactivate(sendData, bot.Bunt)
}
File diff suppressed because it is too large Load Diff
+296
View File
@@ -0,0 +1,296 @@
package telegram
import (
"context"
"fmt"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/eko/gocache/store"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func (bot TipBot) shopsMainMenu(ctx context.Context, shops *Shops) *tb.ReplyMarkup {
browseShopButton := shopKeyboard.Data("🛍 Browse shops", "shops_browse", shops.ID)
shopNewShopButton := shopKeyboard.Data("✅ New Shop", "shops_newshop", shops.ID)
shopSettingsButton := shopKeyboard.Data("⚙️ Settings", "shops_settings", shops.ID)
user := LoadUser(ctx)
buttons := []tb.Row{}
if len(shops.Shops) > 0 {
buttons = append(buttons, shopKeyboard.Row(browseShopButton))
}
if user.Telegram.ID == shops.Owner.Telegram.ID {
buttons = append(buttons, shopKeyboard.Row(shopNewShopButton, shopSettingsButton))
}
shopKeyboard.Inline(
buttons...,
)
return shopKeyboard
}
func (bot TipBot) shopsSettingsMenu(ctx context.Context, shops *Shops) *tb.ReplyMarkup {
shopShopsButton := shopKeyboard.Data("⬅️ Back", "shops_shops", shops.ID)
shopLinkShopButton := shopKeyboard.Data("🔗 Shop links", "shops_linkshop", shops.ID)
shopRenameShopButton := shopKeyboard.Data("⌨️ Rename a shop", "shops_renameshop", shops.ID)
shopDeleteShopButton := shopKeyboard.Data("🚫 Delete shops", "shops_deleteshop", shops.ID)
shopDescriptionShopButton := shopKeyboard.Data("💬 Description", "shops_description", shops.ID)
// // shopResetShopButton := shopKeyboard.Data("⚠️ Delete all shops", "shops_reset", shops.ID)
// buttons := []tb.Row{
// shopKeyboard.Row(shopLinkShopButton),
// shopKeyboard.Row(shopDescriptionShopButton),
// shopKeyboard.Row(shopRenameShopButton),
// shopKeyboard.Row(shopDeleteShopButton),
// // shopKeyboard.Row(shopResetShopButton),
// shopKeyboard.Row(shopShopsButton),
// }
// shopKeyboard.Inline(
// buttons...,
// )
button := []tb.Btn{
shopLinkShopButton,
shopDescriptionShopButton,
shopRenameShopButton,
shopDeleteShopButton,
shopShopsButton,
}
shopKeyboard.Inline(buttonWrapper(button, shopKeyboard, 2)...)
return shopKeyboard
}
// shopItemSettingsMenu builds the buttons of the item settings
func (bot TipBot) shopItemSettingsMenu(ctx context.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
shopItemPriceButton = shopKeyboard.Data("💯 Set price", "shop_itemprice", item.ID)
shopItemDeleteButton = shopKeyboard.Data("🚫 Delete item", "shop_itemdelete", item.ID)
shopItemTitleButton = shopKeyboard.Data("⌨️ Set title", "shop_itemtitle", item.ID)
shopItemAddFileButton = shopKeyboard.Data("💾 Add file", "shop_itemaddfile", item.ID)
shopItemSettingsBackButton = shopKeyboard.Data("⬅️ Back", "shop_itemsettingsback", item.ID)
user := LoadUser(ctx)
buttons := []tb.Row{}
if user.Telegram.ID == shop.Owner.Telegram.ID {
buttons = append(buttons, shopKeyboard.Row(shopItemDeleteButton, shopItemSettingsBackButton))
buttons = append(buttons, shopKeyboard.Row(shopItemTitleButton, shopItemPriceButton))
buttons = append(buttons, shopKeyboard.Row(shopItemAddFileButton))
}
shopKeyboard.Inline(
buttons...,
)
return shopKeyboard
}
// shopItemConfirmBuyMenu builds the buttons to confirm a purchase
func (bot TipBot) shopItemConfirmBuyMenu(ctx context.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
shopItemBuyButton = shopKeyboard.Data(fmt.Sprintf("💸 Pay %d sat", item.Price), "shop_itembuy", item.ID)
shopItemCancelBuyButton = shopKeyboard.Data("⬅️ Back", "shop_itemcancelbuy", item.ID)
buttons := []tb.Row{}
buttons = append(buttons, shopKeyboard.Row(shopItemBuyButton))
buttons = append(buttons, shopKeyboard.Row(shopItemCancelBuyButton))
shopKeyboard.Inline(
buttons...,
)
return shopKeyboard
}
// shopMenu builds the buttons in the item browser
func (bot TipBot) shopMenu(ctx context.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
user := LoadUser(ctx)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
return nil
}
shopShopsButton := shopKeyboard.Data("⬅️ Back", "shops_shops", shop.ShopsID)
shopAddItemButton = shopKeyboard.Data("✅ New item", "shop_additem", shop.ID)
shopItemSettingsButton = shopKeyboard.Data("⚙️ Settings", "shop_itemsettings", item.ID)
shopNextitemButton = shopKeyboard.Data(">", "shop_nextitem", shop.ID)
shopPrevitemButton = shopKeyboard.Data("<", "shop_previtem", shop.ID)
buyButtonText := "📩 Get"
if item.Price > 0 {
buyButtonText = fmt.Sprintf("Buy (%d sat)", item.Price)
}
shopBuyitemButton = shopKeyboard.Data(buyButtonText, "shop_buyitem", item.ID)
buttons := []tb.Row{}
if user.Telegram.ID == shop.Owner.Telegram.ID {
if len(shop.Items) == 0 {
buttons = append(buttons, shopKeyboard.Row(shopAddItemButton))
} else {
buttons = append(buttons, shopKeyboard.Row(shopAddItemButton, shopItemSettingsButton))
}
}
// publicButtons := []tb.Row{}
if len(shop.Items) > 0 {
if shopView.Page == len(shop.Items)-1 {
// last page
shopNextitemButton = shopKeyboard.Data("x", "shop_nextitem", shop.ID)
}
buttons = append(buttons, shopKeyboard.Row(shopPrevitemButton, shopBuyitemButton, shopNextitemButton))
}
buttons = append(buttons, shopKeyboard.Row(shopShopsButton))
shopKeyboard.Inline(
buttons...,
)
return shopKeyboard
}
// makseShopSelectionButtons produces a list of all buttons with a uniqueString ID
func (bot *TipBot) makseShopSelectionButtons(shops []*Shop, uniqueString string) []tb.Btn {
var buttons []tb.Btn
for _, shop := range shops {
buttons = append(buttons, shopKeyboard.Data(shop.Title, uniqueString, shop.ID))
}
return buttons
}
// -------------- ShopView --------------
// getUserShopview returns ShopView object from cache that holds information about the user's current browsing view
func (bot *TipBot) getUserShopview(ctx context.Context, user *lnbits.User) (shopView ShopView, err error) {
sv, err := bot.Cache.Get(fmt.Sprintf("shopview-%d", user.Telegram.ID))
if err != nil {
return
}
shopView = sv.(ShopView)
return
}
func (bot *TipBot) shopViewDeleteAllStatusMsgs(ctx context.Context, user *lnbits.User, start int) (shopView ShopView, err error) {
mutex.Lock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
shopView, err = bot.getUserShopview(ctx, user)
if err != nil {
return
}
statusMessages := shopView.StatusMessages
// delete all status messages from cache
shopView.StatusMessages = append([]*tb.Message{}, statusMessages[0:start]...)
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
deleteStatusMessages(start, statusMessages, bot)
mutex.Unlock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
return
}
func deleteStatusMessages(start int, messages []*tb.Message, bot *TipBot) {
// delete all status messages from telegram
for _, msg := range messages[start:] {
bot.tryDeleteMessage(msg)
}
}
// sendStatusMessage adds a status message to the shopVoew.statusMessages
// slide and sends a status message to the user.
func (bot *TipBot) sendStatusMessage(ctx context.Context, to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
user := LoadUser(ctx)
id := fmt.Sprintf("shopview-delete-%d", user.Telegram.ID)
// write into cache
mutex.Lock(id)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
return nil
}
statusMsg := bot.trySendMessage(to, what, options...)
shopView.StatusMessages = append(shopView.StatusMessages, statusMsg)
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
mutex.Unlock(id)
return statusMsg
}
// sendStatusMessageAndDelete invokes sendStatusMessage and creates
// a ticker to delete all status messages after 5 seconds.
func (bot *TipBot) sendStatusMessageAndDelete(ctx context.Context, to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
user := LoadUser(ctx)
id := fmt.Sprintf("shopview-delete-%d", user.Telegram.ID)
statusMsg := bot.sendStatusMessage(ctx, to, what, options...)
// kick off ticker to remove all messages
ticker := runtime.GetTicker(id, runtime.WithDuration(5*time.Second))
if !ticker.Started {
ticker.Do(func() {
bot.shopViewDeleteAllStatusMsgs(ctx, user, 1)
// removing ticker asap done
runtime.RemoveTicker(id)
})
} else {
ticker.ResetChan <- struct{}{}
}
return statusMsg
}
// --------------- Shop ---------------
// initUserShops is a helper function for creating a Shops for the user in the database
func (bot *TipBot) initUserShops(ctx context.Context, user *lnbits.User) (*Shops, error) {
id := fmt.Sprintf("shops-%d", user.Telegram.ID)
shops := &Shops{
Base: storage.New(storage.ID(id)),
ID: id,
Owner: user,
Shops: []string{},
MaxShops: MAX_SHOPS,
}
runtime.IgnoreError(shops.Set(shops, bot.ShopBunt))
return shops, nil
}
// getUserShops returns the Shops for the user
func (bot *TipBot) getUserShops(ctx context.Context, user *lnbits.User) (*Shops, error) {
tx := &Shops{Base: storage.New(storage.ID(fmt.Sprintf("shops-%d", user.Telegram.ID)))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.ShopBunt)
if err != nil {
log.Errorf("[getUserShops] User: %s (%d): %s", GetUserStr(user.Telegram), user.Telegram.ID, err)
return &Shops{}, err
}
shops := sn.(*Shops)
return shops, nil
}
// addUserShop adds a new Shop to the Shops of a user
func (bot *TipBot) addUserShop(ctx context.Context, user *lnbits.User) (*Shop, error) {
shops, err := bot.getUserShops(ctx, user)
if err != nil {
return &Shop{}, err
}
shopId := fmt.Sprintf("shop-%s", RandStringRunes(10))
shop := &Shop{
Base: storage.New(storage.ID(shopId)),
ID: shopId,
Title: fmt.Sprintf("Shop %d (%s)", len(shops.Shops)+1, shopId),
Owner: user,
Type: "photo",
Items: make(map[string]ShopItem),
LanguageCode: ctx.Value("publicLanguageCode").(string),
ShopsID: shops.ID,
MaxItems: MAX_ITEMS_PER_SHOP,
}
runtime.IgnoreError(shop.Set(shop, bot.ShopBunt))
shops.Shops = append(shops.Shops, shopId)
runtime.IgnoreError(shops.Set(shops, bot.ShopBunt))
return shop, nil
}
// getShop returns the Shop for the given ID
func (bot *TipBot) getShop(ctx context.Context, shopId string) (*Shop, error) {
tx := &Shop{Base: storage.New(storage.ID(shopId))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
// immediatelly set intransaction to block duplicate calls
sn, err := tx.Get(tx, bot.ShopBunt)
if err != nil {
log.Errorf("[getShop] %s", err.Error())
return &Shop{}, err
}
shop := sn.(*Shop)
if shop.Owner == nil {
return &Shop{}, fmt.Errorf("shop has no owner")
}
return shop, nil
}
+10 -7
View File
@@ -4,14 +4,16 @@ import (
"context"
"errors"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"strconv"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
tb "gopkg.in/tucnak/telebot.v2"
"github.com/LightningTipBot/LightningTipBot/internal/str"
tb "gopkg.in/lightningtipbot/telebot.v2"
"gorm.io/gorm"
)
@@ -22,7 +24,7 @@ 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)
log.Printf("[⭐️ /start] New user: %s (%d)\n", GetUserStr(m.Sender), m.Sender.ID)
walletCreationMsg, err := bot.Telegram.Send(m.Sender, Translate(ctx, "startSettingWalletMessage"))
user, err := bot.initWallet(m.Sender)
if err != nil {
@@ -78,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
}
@@ -92,16 +94,17 @@ func (bot TipBot) createWallet(user *lnbits.User) error {
user.Name = u.Name
wallet, err := bot.Client.Wallets(*user)
if err != nil {
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err)
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err.Error())
log.Errorln(errormsg)
return err
}
user.Wallet = &wallet[0]
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
user.Initialized = false
user.CreatedAt = time.Now()
err = UpdateUserRecord(user, bot)
if err != nil {
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err)
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err.Error())
log.Errorln(errormsg)
return err
}
+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,
}
}
+115 -11
View File
@@ -1,44 +1,148 @@
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"
)
func (bot TipBot) tryForwardMessage(to tb.Recipient, what tb.Editable, options ...interface{}) (msg *tb.Message) {
msg, err := bot.Telegram.Forward(to, what, options...)
// appendMainMenu will check if to (recipient) ID is from private or group chat.
// this function will only add a keyboard if this is a private chat and no force reply.
func appendMainMenu(to int64, options []interface{}) []interface{} {
appendKeyboard := true
for _, option := range options {
if option == tb.ForceReply {
appendKeyboard = false
}
switch option.(type) {
case *tb.ReplyMarkup:
appendKeyboard = false
//option.(*tb.ReplyMarkup).ReplyKeyboard = mainMenu.ReplyKeyboard
//if option.(*tb.ReplyMarkup).InlineKeyboard == nil {
// options = append(options[:i], options[i+1:]...)
//}
}
}
// to > 0 is private chats
if to > 0 && appendKeyboard {
options = append(options, mainMenu)
}
return options
}
// getChatIdFromRecipient will parse the recipient to int64
func getChatIdFromRecipient(to tb.Recipient) (int64, error) {
chatId, err := strconv.ParseInt(to.Recipient(), 10, 64)
if err != nil {
log.Errorln(err.Error())
return 0, err
}
return chatId, nil
}
func (bot TipBot) tryForwardMessage(to tb.Recipient, what tb.Editable, options ...interface{}) (msg *tb.Message) {
rate.CheckLimit(to)
// ChatId is used for the keyboard
chatId, err := getChatIdFromRecipient(to)
if err != nil {
log.Errorf("[tryForwardMessage] error converting message recipient to int64: %v", err)
return
}
msg, err = bot.Telegram.Forward(to, what, appendMainMenu(chatId, options)...)
if err != nil {
log.Warnln(err.Error())
}
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 := getChatIdFromRecipient(to)
if err != nil {
log.Errorln(err.Error())
log.Errorf("[trySendMessage] error converting message recipient to int64: %v", err)
return
}
msg, err = bot.Telegram.Send(to, what, appendMainMenu(chatId, options)...)
if err != nil {
log.Warnln(err.Error())
}
return
}
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, appendMainMenu(to.Chat.ID, options)...)
if err != nil {
log.Errorln(err.Error())
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...)
rate.CheckLimit(to)
var err error
_, chatId := to.MessageSig()
msg, err = bot.Telegram.Edit(to, what, appendMainMenu(chatId, options)...)
if err != nil {
log.Errorln(err.Error())
log.Warnln(err.Error())
}
return
}
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.Errorln(err.Error())
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
}
+78 -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
}
@@ -33,11 +36,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 {
bot.lnurlEnterAmountHandler(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
}
}
+17 -18
View File
@@ -3,14 +3,15 @@ package telegram
import (
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func helpTipUsage(ctx context.Context, errormsg string) string {
@@ -30,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.Telegram))
// check and print all commands
bot.anyTextHandler(ctx, m)
user := LoadUser(ctx)
@@ -41,7 +40,7 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
// only if message is a reply
if !m.IsReply() {
NewMessage(m, WithDuration(0, bot.Telegram))
bot.tryDeleteMessage(m)
bot.trySendMessage(m.Sender, helpTipUsage(ctx, Translate(ctx, "tipDidYouReplyMessage")))
bot.trySendMessage(m.Sender, Translate(ctx, "tipInviteGroupMessage"))
return
@@ -49,7 +48,7 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
if ok, err := TipCheckSyntax(ctx, m); !ok {
bot.trySendMessage(m.Sender, helpTipUsage(ctx, err))
NewMessage(m, WithDuration(0, bot.Telegram))
NewMessage(m, WithDuration(0, bot))
return
}
@@ -58,9 +57,9 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
if err != nil || amount < 1 {
errmsg := fmt.Sprintf("[/tip] Error: Tip amount not valid.")
// immediately delete if the amount is bullshit
NewMessage(m, WithDuration(0, bot.Telegram))
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, helpTipUsage(ctx, Translate(ctx, "tipValidAmountMessage")))
log.Errorln(errmsg)
log.Warnln(errmsg)
return
}
@@ -70,11 +69,10 @@ 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 {
NewMessage(m, WithDuration(0, bot.Telegram))
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, Translate(ctx, "tipYourselfMessage"))
return
}
@@ -110,24 +108,23 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
t.Memo = transactionMemo
success, err := t.Send()
if !success {
NewMessage(m, WithDuration(0, bot.Telegram))
bot.trySendMessage(m.Sender, Translate(ctx, "tipErrorMessage"))
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err)
log.Errorln(errMsg)
NewMessage(m, WithDuration(0, bot))
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
}
// 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
log.Warnln(errmsg)
}
// forward tipped message to user once
@@ -139,5 +136,7 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
if len(tipMemo) > 0 {
bot.trySendMessage(to.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(tipMemo)))
}
// 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
+42 -53
View File
@@ -7,33 +7,30 @@ import (
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
tb "gopkg.in/tucnak/telebot.v2"
)
const (
balanceTooLowMessage = "Your balance is too low."
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)
@@ -51,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,
@@ -73,49 +70,40 @@ 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 {
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
log.Errorln(errmsg)
return false, err
}
// check if fromUser has balance
if balance < amount {
errmsg := fmt.Sprintf(balanceTooLowMessage)
log.Errorf("Balance of user %s too low", fromUserStr)
return false, fmt.Errorf(errmsg)
}
// // check if fromUser has balance
// balance, err := bot.GetUserBalance(from)
// if err != nil {
// errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
// log.Errorln(errmsg)
// return false, err
// }
// // check if fromUser has balance
// if balance < amount {
// errmsg := fmt.Sprintf("balance too low.")
// log.Warnf("Balance of user %s too low", fromUserStr)
// return false, fmt.Errorf(errmsg)
// }
t.ToWallet = to.ID
t.ToLNbitsID = to.ID
@@ -128,15 +116,16 @@ 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)
log.Errorln(errmsg)
errmsg := fmt.Sprintf("[Send] Payment failed (%s to %s of %d sat): %s", fromUserStr, toUserStr, amount, err.Error())
log.Warnf(errmsg)
return false, err
}
return true, err
+31 -23
View File
@@ -3,25 +3,26 @@ package telegram
import (
"errors"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/eko/gocache/store"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v2"
"gorm.io/gorm"
)
func SetUserState(user *lnbits.User, bot TipBot, stateKey lnbits.UserStateKey, stateData string) {
func SetUserState(user *lnbits.User, bot *TipBot, stateKey lnbits.UserStateKey, stateData string) {
user.StateKey = stateKey
user.StateData = stateData
bot.Database.Table("users").Where("name = ?", user.Name).Update("state_key", user.StateKey).Update("state_data", user.StateData)
UpdateUserRecord(user, *bot)
}
func ResetUserState(user *lnbits.User, bot TipBot) {
func ResetUserState(user *lnbits.User, bot *TipBot) {
user.ResetState()
bot.Database.Table("users").Where("name = ?", user.Name).Update("state_key", 0).Update("state_data", "")
UpdateUserRecord(user, *bot)
}
func GetUserStr(user *tb.User) string {
@@ -59,11 +60,19 @@ func appendUinqueUsersToSlice(slice []*tb.User, i *tb.User) []*tb.User {
return append(slice, i)
}
func (bot *TipBot) GetUserBalance(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.(int64)
return cachedBalance, nil
}
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)
errmsg := fmt.Sprintf("[GetUserBalance] Error: Couldn't fetch user %s's info from LNbits: %s", GetUserStr(user.Telegram), err.Error())
log.Errorln(errmsg)
return
}
@@ -73,21 +82,20 @@ 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},
)
return
}
// copyLowercaseUser will create a coy user and cast username to lowercase.
func (bot *TipBot) copyLowercaseUser(u *tb.User) *tb.User {
userCopy := *u
userCopy.Username = strings.ToLower(u.Username)
return &userCopy
}
func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, error) {
userCopy := bot.copyLowercaseUser(tbUser)
user := &lnbits.User{Telegram: userCopy}
user := &lnbits.User{Telegram: tbUser}
userStr := GetUserStr(tbUser)
log.Printf("[CreateWalletForTelegramUser] Creating wallet for user %s ... ", userStr)
err := bot.createWallet(user)
@@ -96,9 +104,9 @@ func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, e
log.Errorln(errmsg)
return user, err
}
tx := bot.Database.Save(user)
if tx.Error != nil {
return nil, tx.Error
err = UpdateUserRecord(user, *bot)
if err != nil {
return nil, err
}
log.Printf("[CreateWalletForTelegramUser] Wallet created for user %s. ", userStr)
return user, nil
+4 -1
View File
@@ -1,6 +1,7 @@
package main
import (
"net/http"
"runtime/debug"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits/webhook"
@@ -8,11 +9,12 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/price"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
log "github.com/sirupsen/logrus"
_ "net/http/pprof"
)
// setLogger will initialize the log format
func setLogger() {
log.SetLevel(log.InfoLevel)
log.SetLevel(log.TraceLevel)
customFormatter := new(log.TextFormatter)
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
customFormatter.FullTimestamp = true
@@ -22,6 +24,7 @@ func setLogger() {
func main() {
// set logger
setLogger()
go http.ListenAndServe("0.0.0.0:6060", nil)
defer withRecovery()
bot := telegram.NewBot()
webhook.NewServer(&bot)
+1 -1
View File
@@ -21,7 +21,7 @@ func IsInvoice(message string) bool {
func IsLnurl(message string) bool {
message = strings.ToLower(message)
if strings.HasPrefix(message, "lnurl") {
if strings.HasPrefix(message, "lnurl") || strings.HasPrefix(message, "lightning:lnurl") {
// string must be a single word
if !strings.Contains(message, " ") {
return true
+54 -15
View File
@@ -40,6 +40,7 @@ sendButtonMessage = """✅ Senden"""
payButtonMessage = """✅ Bezahlen"""
payReceiveButtonMessage = """💸 Bezahlen"""
receiveButtonMessage = """✅ Empfangen"""
withdrawButtonMessage = """✅ Abheben"""
cancelButtonMessage = """🚫 Abbrechen"""
collectButtonMessage = """✅ Einsammeln"""
nextButtonMessage = """Vor"""
@@ -81,7 +82,7 @@ infoHelpMessage = """ℹ️ *Info*"""
infoYourLightningAddress = """Deine Lightning Adresse ist `%s`"""
basicsMessage = """🧡 *Bitcoin*
_Bitcoin ist die Währung des Internets. Es ist offen für jeden, dezentral und es gibt niemanden, der Bitcoin kontrolliert. Bitcoin ist hartes Geld, was schneller, sicherer, und fairer ist, als das klassische Finanzsystem._
_Bitcoin ist die Währung des Internets. Bitcoin ist offen für jeden, ist dezentral, und es gibt niemanden, der Bitcoin kontrolliert. Bitcoin ist hartes Geld, welches schneller, sicherer, und fairer ist, als das klassische Finanzsystem._
🧮 *Ökonomie*
_Die kleinste Einheit von Bitcoin sind Satoshis (sat) und 100,000,000 sat = 1 Bitcoin. Es wird niemals mehr als 21 Millionen Bitcoin geben. Der Fiatgeld-Wert von Bitcoin kann sich täglich ändern. Wenn du jedoch auf einem Bitcoin-Standard lebst, wird 1 sat für immer 1 sat Wert sein._
@@ -90,7 +91,7 @@ _Die kleinste Einheit von Bitcoin sind Satoshis (sat) und 100,000,000 sat = 1 Bi
_Das Lightning Netzwerk ist ein Bezahlprotokoll, das schnelle und günstige Bitcoin Zahlungen erlaubt, die fast keine Energie kosten. Dadurch skaliert Bitcoin auf Milliarden von Menschen weltweit._
📲 *Lightning Wallets*
_Dein Geld auf diesem Bot kannst du an jedes andere Lightning Wallet der Welt versenden. Empfholene Lightning Wallets für dein Handy sind _ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (non-custodial), or_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(einfach)_.
_Dein Geld auf diesem Bot kannst du an jedes andere Lightning Wallet der Welt versenden. Empfohlene Lightning Wallets für dein Handy sind _ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (eigene Verwahrung), oder_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(einfach)_.
📄 *Open Source*
_Dieser Bot ist kostenlose_ [Open Source](https://github.com/LightningTipBot/LightningTipBot) _Software. Du kannst ihn auf deinem eigenen Rechner laufen lassen und für deine eigene Community betreiben._
@@ -99,31 +100,38 @@ _Dieser Bot ist kostenlose_ [Open Source](https://github.com/LightningTipBot/Lig
_Füge den Bot in deine Telegram Gruppenchats hinzu, um Nachrichten ein /tip zu senden. Wenn der Bot Admin der Gruppe ist, wird er auch den Chat aufräumen, indem er manche Befehle nach Ausführung löscht._
🏛 *Bedingungen*
_Wir sind keine Verwalter deines Geldes. Wir werden in deinem besten Interesse handeln, aber sind uns auch dessen bewusst, dass die Situation ohne KYC etwas kompliziert ist. Solange wir keine andere Lösung gefunden haben, werden wir alle Beträge auf diesem Bot als Spenden betrachten. Gebe uns nicht dein ganzes Geld. Sei dir dessen bewusst, dass dieser Bot immer noch in der Betaphase ist. Benutzung auf eigene Gefahr._
_Wir sind keine Verwahrer deines Geldes. Wir werden in deinem besten Interesse handeln, aber sind uns auch dessen bewusst, dass die Situation ohne KYC etwas kompliziert ist. Solange wir keine andere Lösung gefunden haben, werden wir alle Beträge auf diesem Bot als Spenden betrachten. Gebe uns nicht dein ganzes Geld. Sei dir dessen bewusst, dass dieser Bot immer noch in der Betaphase ist. Benutzung auf eigene Gefahr._
❤️ *Spenden*
_Dieser Bot erhebt keine Gebühren, kostet aber Satoshis um betrieben zu werden. Wenn du den Bot magst, kannst das Projekt mit eine Spende unterstützen. Um zu spenden, gebe ein: _ `/donate 1000`"""
helpNoUsernameMessage = """👋 Bitte setze einen Telegram Benutzernamen."""
helpNoUsernameMessage = """👋 Wähle einen Benutzernamen in den Telegram Einstellungen."""
advancedMessage = """%s
👉 *Inline Befehle*
*send* 💸 Sende sats an einen Chat: `%s send <betrag> [<memo>]`
*receive* 🏅 Bitte um Zahlung: `%s receive <betrag> [<memo>]`
*faucet* 🚰 Erzeuge einen Zapfhahn: `%s faucet <gesamt> <pro_user>`
*send* 💸 Sende sats an einen Chat: `%s send <betrag> [<user>] [<memo>]`
*receive* 🏅 Bitte um Zahlung: `... receive <betrag> [<user>] [<memo>]`
*faucet* 🚰 Erzeuge einen Zapfhahn: `... faucet <gesamt> <pro_user> [<memo>]`
*tipjar* 🍯 Erzeuge eine Spendendose: `... tipjar <gesamt> <pro_user> [<memo>]`
📖 Du kannst Inline Befehle in jedem Chat verwenden, sogar in privaten Nachrichten. Warte eine Sekunde, nachdem du den Befehl eingegeben hast und *klicke* auf das Ergebnis, statt Enter einzugeben.
⚙️ *Fortgeschrittene Befehle*
*/link* 🔗 Verbinde dein Wallet mit [BlueWallet](https://bluewallet.io/) oder [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Lnurl empfangen oder senden: `/lnurl` or `/lnurl <lnurl>`
*/faucet* 🚰 Erzeuge einen Zapfhahn `/faucet <gesamt> <pro_user>`"""
*/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..."""
startWalletCreatedMessage = """🧮 Wallet erstellt."""
startWalletCreatedMessage = """🧮 Wallet erzeugt."""
startWalletReadyMessage = """✅ *Dein Wallet ist bereit.*"""
startWalletErrorMessage = """🚫 Fehler beim einrichten deines Wallets. Bitte versuche es später noch einmal."""
startNoUsernameMessage = """☝️ Es sieht so aus, als hättest du noch keinen Telegram @usernamen. Das ist ok, du brauchst keinen, um diesen Bot zu verwenden. Um jedoch alle Funktionen verwenden zu können, solltest du dir einen Usernamen in den Telegram Einstellungen setzen. Gebe danach ein mal /balance ein, damit der Bot seine Informationen über dich aktualisieren kann."""
@@ -175,7 +183,7 @@ invoiceEnterAmountMessage = """Hast du einen Betrag eingegeben?"""
invoiceValidAmountMessage = """Hast du einen gültigen Betrag eingegeben?"""
invoiceHelpText = """📖 Ups, das hat nicht geklappt. %s
*Befehl:* `/invoice <amount> [<memo>]`
*Befehl:* `/invoice <betrag> [<memo>]`
*Beispiel:* `/invoice 1000 Thank you!`"""
# PAY
@@ -224,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."""
lnurlEnterAmountMessage = """⌨️ 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*
@@ -237,7 +252,7 @@ walletConnectMessage = """🔗 *Verbinde dein Wallet*
⚠️ Teile diese URL und den QR code mit niemandem! Jeder, der darauf Zugriff hat, hat auch Zugriff auf dein Konto.
- *BlueWallet:* Drücke *New wallet*, *Import wallet*, *Scan or import a file*, und scanne den QR Code.
- *Zeus:* Kiere die URL unten, drücke *Add a new node*, *Import* (die URL), *Save Node Config*."""
- *Zeus:* Kopiere die URL unten, drücke *Add a new node*, *Import* (die URL), *Save Node Config*."""
couldNotLinkMessage = """🚫 Konnte dein Wallet nicht verbinden. Bitte versuche es später noch einmal."""
# FAUCET
@@ -259,7 +274,7 @@ inlineFaucetInvalidPeruserAmountMessage = """🚫 Die Pro-User Menge muss ein na
inlineFaucetInvalidAmountMessage = """🚫 Ungültige Menge."""
inlineFaucetSentMessage = """🚰 %d sat an %s gesendet."""
inlineFaucetReceivedMessage = """🚰 %s hat dir %d sat gesendet."""
inlineFaucetHelpFaucetInGroup = """Erzuge einen Zapfhahn in einer Gruppe, wo der Bot eingeladen ist oder benutze einen 👉 Inline Bommand (/advanced für mehr)."""
inlineFaucetHelpFaucetInGroup = """Erzeuge einen Zapfhahn in einer Gruppe, wo der Bot eingeladen ist oder benutze einen 👉 Inline Befehl (/advanced für mehr)."""
inlineFaucetHelpText = """📖 Ups, das hat nicht geklappt. %s
*Befehl:* `/faucet <gesamt> <pro_user>`
@@ -268,7 +283,7 @@ inlineFaucetHelpText = """📖 Ups, das hat nicht geklappt. %s
# INLINE SEND
inlineQuerySendTitle = """💸 Sende Zahlungen in einem Chat."""
inlineQuerySendDescription = """Befehl: @%s send <betrag> [<memo>]"""
inlineQuerySendDescription = """Befehl: @%s send <betrag> [<user>] [<memo>]"""
inlineResultSendTitle = """💸 Sende %d sat."""
inlineResultSendDescription = """👉 Klicke hier um %d sat in diesen Chat zu senden."""
@@ -284,7 +299,7 @@ inlineSendBalanceLowMessage = """🚫 Dein Guthaben reicht nicht aus."""
# INLINE RECEIVE
inlineQueryReceiveTitle = """🏅 Empfange eine Zahlung in einem Chat."""
inlineQueryReceiveDescription = """Befehl: @%s receive <betrag> [<memo>]"""
inlineQueryReceiveDescription = """Befehl: @%s receive <betrag> [<pro_user>] [<memo>]"""
inlineResultReceiveTitle = """🏅 Empfange %d sat."""
inlineResultReceiveDescription = """👉 Klicke hier um eine Zahlung von %d sat zu empfangen."""
@@ -295,3 +310,27 @@ inlineReceiveCreateWalletMessage = """Chatte mit %s 👈 um dein Wallet zu verwa
inlineReceiveYourselfMessage = """📖 Du kannst dich nicht selbst bezahlen."""
inlineReceiveFailedMessage = """🚫 Empfangen fehlgeschlagen."""
inlineReceiveCancelledMessage = """🚫 Empfangen abgebrochen."""
# TIPJAR
inlineQueryTipjarTitle = """🍯 Erzeuge eine Spendendose."""
inlineQueryTipjarDescription = """Befehl: @%s tipjar <betrag> <pro_user>"""
inlineResultTipjarTitle = """🍯 Erzeuge eine Spendendose für %d sat."""
inlineResultTipjarDescription = """👉 Klicke hier um eine Spendendose zu erzeugen."""
inlineTipjarMessage = """Drücke 💸 up *%d sat* in die Spendendose von %s zu *zahlen*.
🙏 Gespendet: *%d*/%d sat (von %d Benutzern)
%s"""
inlineTipjarEndedMessage = """🍯 %s's Spendendose is voll ⭐️\n\n🏅 %d sat gespendet von %d Nutzern."""
inlineTipjarAppendMemo = """\n✉️ %s"""
inlineTipjarCancelledMessage = """🚫 Spendendose abgebrochen."""
inlineTipjarInvalidPeruserAmountMessage = """🚫 Die Pro-User Menge muss ein natürlicher Teiler der Gesamtmenge sein."""
inlineTipjarInvalidAmountMessage = """🚫 Ungültige Menge."""
inlineTipjarSentMessage = """🍯 %d sat an %s gesendet."""
inlineTipjarReceivedMessage = """🍯 %s hat dir %d sat gesendet."""
inlineTipjarHelpTipjarInGroup = """Erzeuge eine Spendendose in einer Gruppe, wo der Bot eingeladen ist oder benutze einen 👉 Inline Befehl (/advanced für mehr)."""
inlineTipjarHelpText = """📖 Ups, das hat nicht geklappt. %s
*Befehl:* `/tipjar <betrag> <pro_user>`
*Beispiel:* `/tipjar 210 21`"""
+53 -9
View File
@@ -40,6 +40,7 @@ sendButtonMessage = """✅ Send"""
payButtonMessage = """✅ Pay"""
payReceiveButtonMessage = """💸 Pay"""
receiveButtonMessage = """✅ Receive"""
withdrawButtonMessage = """✅ Withdraw"""
cancelButtonMessage = """🚫 Cancel"""
collectButtonMessage = """✅ Collect"""
nextButtonMessage = """Next"""
@@ -57,6 +58,9 @@ saveButtonMessage = """Save"""
deleteButtonMessage = """Delete"""
infoButtonMessage = """Info"""
cancelButtonEmoji = """🚫"""
payButtonEmoji = """💸"""
# HELP
helpMessage = """⚡️ *Wallet*
@@ -104,21 +108,29 @@ _We are not custodian of your funds. We will act in your best interest but we're
❤️ *Donate*
_This bot charges no fees but costs satoshis to operate. If you like the bot, please consider supporting this project with a donation. To donate, use_ `/donate 1000`"""
helpNoUsernameMessage = """👋 Please set a Telegram username."""
helpNoUsernameMessage = """👋 Please, set a Telegram username."""
advancedMessage = """%s
👉 *Inline commands*
*send* 💸 Send sats to chat: `%s send <amount> [<memo>]`
*receive* 🏅 Request a payment: `%s receive <amount> [<memo>]`
*faucet* 🚰 Create a faucet: `%s faucet <capacity> <per_user>`
*send* 💸 Send sats to chat: `%s send <amount> [<user>] [<memo>]`
*receive* 🏅 Request a payment: `... receive <amount> [<user>] [<memo>]`
*faucet* 🚰 Create a faucet: `... faucet <capacity> <per_user> [<memo>]`
*tipjar* 🍯 Create a tipjar: `... tipjar <capacity> <per_user> [<memo>]`
📖 You can use inline commands in every chat, even in private conversations. Wait a second after entering an inline command and *click* the result, don't press enter.
⚙️ *Advanced commands*
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Lnurl receive or pay: `/lnurl` or `/lnurl <lnurl>`
*/faucet* 🚰 Create a faucet `/faucet <capacity> <per_user>`"""
*/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
@@ -224,12 +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."""
lnurlEnterAmountMessage = """⌨️ Enter an amount between %d and %d sat."""
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*
@@ -238,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
@@ -268,7 +288,7 @@ inlineFaucetHelpText = """📖 Oops, that didn't work. %s
# INLINE SEND
inlineQuerySendTitle = """💸 Send payment to a chat."""
inlineQuerySendDescription = """Usage: @%s send <amount> [<memo>]"""
inlineQuerySendDescription = """Usage: @%s send <amount> [<user>] [<memo>]"""
inlineResultSendTitle = """💸 Send %d sat."""
inlineResultSendDescription = """👉 Click to send %d sat to this chat."""
@@ -284,7 +304,7 @@ inlineSendBalanceLowMessage = """🚫 Your balance is too low."""
# INLINE RECEIVE
inlineQueryReceiveTitle = """🏅 Request a payment in a chat."""
inlineQueryReceiveDescription = """Usage: @%s receive <amount> [<memo>]"""
inlineQueryReceiveDescription = """Usage: @%s receive <amount> [<user>] [<memo>]"""
inlineResultReceiveTitle = """🏅 Receive %d sat."""
inlineResultReceiveDescription = """👉 Click to request a payment of %d sat."""
@@ -295,3 +315,27 @@ inlineReceiveCreateWalletMessage = """Chat with %s 👈 to manage your wallet.""
inlineReceiveYourselfMessage = """📖 You can't pay to yourself."""
inlineReceiveFailedMessage = """🚫 Receive failed."""
inlineReceiveCancelledMessage = """🚫 Receive cancelled."""
# TIPJAR
inlineQueryTipjarTitle = """🍯 Create a tipjar."""
inlineQueryTipjarDescription = """Usage: @%s tipjar <capacity> <per_user>"""
inlineResultTipjarTitle = """🍯 Create a %d sat tipjar."""
inlineResultTipjarDescription = """👉 Click here to create a tipjar in this chat."""
inlineTipjarMessage = """Press 💸 to *pay %d sat* to this tipjar by %s.
🙏 Given: *%d*/%d sat (by %d users)
%s"""
inlineTipjarEndedMessage = """🍯 %s's tipjar is full ⭐️\n\n🏅 %d sat given by %d users."""
inlineTipjarAppendMemo = """\n✉️ %s"""
inlineTipjarCancelledMessage = """🚫 Tipjar cancelled."""
inlineTipjarInvalidPeruserAmountMessage = """🚫 Peruser amount not divisor of capacity."""
inlineTipjarInvalidAmountMessage = """🚫 Invalid amount."""
inlineTipjarSentMessage = """🍯 %d sat sent to %s."""
inlineTipjarReceivedMessage = """🍯 %s sent you %d sat."""
inlineTipjarHelpTipjarInGroup = """Create a tipjar in a group with the bot inside or use 👉 inline command (/advanced for more)."""
inlineTipjarHelpText = """📖 Oops, that didn't work. %s
*Usage:* `/tipjar <capacity> <per_user>`
*Example:* `/tipjar 210 21`"""
+48 -9
View File
@@ -17,7 +17,7 @@ linkCommandStr = """enlace"""
lnurlCommandStr = """lnurl"""
faucetCommandStr = """grifo"""
tipjarCommandStr = """bote"""
tipjarCommandStr = """alcancía"""
receiveCommandStr = """recibir"""
hideCommandStr = """ocultar"""
volcanoCommandStr = """volcán"""
@@ -109,20 +109,28 @@ helpNoUsernameMessage = """👋 Por favor, pon un nombre de usuario de Telegram.
advancedMessage = """%s
👉 *Comandos Inline*
*send* 💸 Enviar sats al chat: `%s send <monto> [<memo>]`
*receive* 🏅 Solicita un pago: `%s receive <monto> [<memo>]`.
*faucet* 🚰 Crear un grifo: `%s faucet <capacidad> <por_usuario>`.
*send* 💸 Enviar sats al chat: `%s send <monto> [<usario>] [<memo>]`
*receive* 🏅 Solicita un pago: `... receive <monto> [<usario>] [<memo>]`
*faucet* 🚰 Crear un grifo: `... faucet <capacidad> <por_usuario> [<memo>]`
*tipjar* 🍯 Crear un tipjar: `... tipjar <capacidad> <por_usuario> [<memo>]`
📖 Puedes usar comandos _inline_ en todos los chats, incluso en las conversaciones privadas. Espera un segundo después de introducir un comando _inline_ y *haz clic* en el resultado, no pulses enter.
⚙️ *Comandos avanzados*
*/link* 🔗 Enlaza tu monedero a [ BlueWallet ](https://bluewallet.io/) o [ Zeus ](https://zeusln.app/)
*/lnurl* ⚡️ Lnurl recibir o pagar: `/lnurl` o `/lnurl <lnurl>`
*/faucet* 🚰 Crear un grifo: `%s faucet <capacidad> <por_usuario>`"""
*/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."""
@@ -224,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."""
lnurlEnterAmountMessage = """⌨️ 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*
@@ -268,7 +283,7 @@ inlineFaucetHelpText = """📖 Oops, eso no funcionó. %s
# INLINE SEND
inlineQuerySendTitle = """💸 Enviar el pago a un chat."""
inlineQuerySendDescription = """Uso: @%s send <monto> [<memo>]"""
inlineQuerySendDescription = """Uso: @%s send <monto> [<usario>] [<memo>]"""
inlineResultSendTitle = """💸 Enviar %d sat."""
inlineResultSendDescription = """👉 Haga clic para enviar %d sat a este chat."""
@@ -284,7 +299,7 @@ inlineSendBalanceLowMessage = """🚫 Tu saldo es demasiado bajo."""
# INLINE RECEIVE
inlineQueryReceiveTitle = """🏅 Solicita un pago en un chat."""
inlineQueryReceiveDescription = """Uso: @%s receive <monto> [<memo>]"""
inlineQueryReceiveDescription = """Uso: @%s receive <monto> [<usario>] [<memo>]"""
inlineResultReceiveTitle = """🏅 Recibir %d sat."""
inlineResultReceiveDescription = """👉 Haga clic para solicitar un pago de %d sat."""
@@ -295,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`"""
+14 -7
View File
@@ -109,16 +109,24 @@ helpNoUsernameMessage = """👋 Définissez un nom d'utilisateur sur Telegram af
advancedMessage = """%s
👉 *Inline commands*
*send* 💸 Envoyer des sats : `%s send <montant> [<memo>]`
*receive* 🏅 Demander un paiement : `%s receive <montant> [<memo>]`
*faucet* 🚰 Créer un faucet: `%s faucet <capacité> <par_utilisateur>`
*send* 💸 Envoyer des sats : `%s send <montant> [<utilisateur>] [<memo>]`
*receive* 🏅 Demander un paiement : `... receive <montant> [<utilisateur>] [<memo>]`
*faucet* 🚰 Créer un faucet: `... faucet <capacité> <par_utilisateur> [<memo>]`
*tipjar* 🍯 Créer un tipjar: `... tipjar <capacité> <par_utilisateur> [<memo>]`
📖 Vous pouvez utiliser ces commandes dans tous les chats et même dans les conversations privées. Attendez une seconde après avoir tapé une commandé puis *click* sur le résultat, n'appuyez pas sur entrée.
⚙️ *Commandes avancées*
*/link* 🔗 Lier votre wallet à [BlueWallet](https://bluewallet.io/) ou [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Lnurl recevoir ou payer: `/lnurl` ou `/lnurl <lnurl>`
*/faucet* 🚰 Créer un faucet `/faucet <capacité> <par_utilisateur>`"""
*/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
@@ -224,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."""
lnurlEnterAmountMessage = """⌨️ Choisissez un montant entre %d et %d sat."""
lnurlHelpText = """📖 Oops, cela n'a pas fonctionné. %s
*Usage:* `/lnurl [montant] <lnurl>`
@@ -268,7 +275,7 @@ inlineFaucetHelpText = """📖 Oops, cela n'a pas fonctionné
# INLINE SEND
inlineQuerySendTitle = """💸 Envoyez des paiements dans un chat."""
inlineQuerySendDescription = """Usage: @%s send <montant> [<memo>]"""
inlineQuerySendDescription = """Usage: @%s send <montant> [<utilisateur>] [<memo>]"""
inlineResultSendTitle = """💸 Envoyé %d sat."""
inlineResultSendDescription = """👉 Clique pour envoyer %d sat sur ce chat."""
@@ -284,7 +291,7 @@ inlineSendBalanceLowMessage = """🚫 Votre solde est trop bas."""
# INLINE RECEIVE
inlineQueryReceiveTitle = """🏅 Demander un paiement dans un chat."""
inlineQueryReceiveDescription = """Usage: @%s receive <montant> [<memo>]"""
inlineQueryReceiveDescription = """Usage: @%s receive <montant> [<utilisateur>] [<memo>]"""
inlineResultReceiveTitle = """🏅 Recevoir %d sat."""
inlineResultReceiveDescription = """👉 Cliquez ici pour recevoir un paiement de %d sat."""
+312
View File
@@ -0,0 +1,312 @@
# COMMANDS
helpCommandStr = """bantuan"""
basicsCommandStr = """dasar"""
tipCommandStr = """tip"""
balanceCommandStr = """saldo"""
sendCommandStr = """kirim"""
invoiceCommandStr = """invoice"""
payCommandStr = """bayar"""
donateCommandStr = """donasi"""
advancedCommandStr = """lanjutan"""
transactionsCommandStr = """transaksi"""
logCommandStr = """log"""
listCommandStr = """daftar"""
linkCommandStr = """link"""
lnurlCommandStr = """lnurl"""
faucetCommandStr = """keran"""
tipjarCommandStr = """tipjar"""
receiveCommandStr = """terima"""
hideCommandStr = """sembunyikan"""
volcanoCommandStr = """volcano"""
showCommandStr = """munculkan"""
optionsCommandStr = """pilihan"""
settingsCommandStr = """pengaturan"""
saveCommandStr = """simpan"""
deleteCommandStr = """hapus"""
infoCommandStr = """info"""
# NOTIFICATIONS
cantDoThatMessage = """Kamu tidak bisa melakukan itu."""
cantClickMessage = """Kamu tidak dapat menekan tombol itu."""
balanceTooLowMessage = """Saldo mu terlalu rendah."""
# BUTTONS
sendButtonMessage = """✅ Kirim"""
payButtonMessage = """✅ Bayar"""
payReceiveButtonMessage = """💸 Bayar"""
receiveButtonMessage = """✅ Terima"""
cancelButtonMessage = """🚫 Batal"""
collectButtonMessage = """✅ Ambil"""
nextButtonMessage = """Lanjut"""
backButtonMessage = """Kembali"""
acceptButtonMessage = """Setuju"""
denyButtonMessage = """Tolak"""
tipButtonMessage = """Tip"""
revealButtonMessage = """Perlihatkan"""
showButtonMessage = """Munculkan"""
hideButtonMessage = """Sembunyikan"""
joinButtonMessage = """Bergabung"""
optionsButtonMessage = """Pilihan"""
settingsButtonMessage = """Pengaturan"""
saveButtonMessage = """Simpan"""
deleteButtonMessage = """Hapus"""
infoButtonMessage = """Info"""
# HELP
helpMessage = """⚡️ *Dompet*
_Bot ini adalah sebuah dompet Bitcoin Lightning yang dapat mengirimkan tip melalui Telegram. Untuk memberi tip, tambahkan bot ke chat grup. Unit dasar dari tip adalah Satoshi (sat). 100,000,000 sat = 1 Bitcoin. Ketik 📚 /basics untuk informasi lebih banyak._
❤️ *Donasi*
_Bot ini tidak memungut biaya tapi memerlukan Satoshi untuk bekerja. Kalau kamu menyukai bot ini, tolong pertimbangkan mendukung proyek ini dengan donasi. Untuk melakukan donasi, pakai_ `/donate 1000`
%s
⚙️ *Commands*
*/tip* 🏅 Membalas sebuah pesan untuk memberi tip: `/tip <jumlah> [<berita>]`
*/balance* 👑 Memeriksa saldo mu: `/balance`
*/send* 💸 Mengirim dana ke seorang pengguna: `/send <jumlah> @user or user@ln.tips [<berita>]`
*/invoice* ⚡️ Menerima menggunakan Lightning: `/invoice <jumlah> [<berita>]`
*/pay* ⚡️ Membayar dengan Lightning: `/pay <invoice>`
*/donate* ❤️ Memberi donasi ke proyek: `/donate 1000`
*/advanced* 🤖 Fitur lanjutan.
*/help* 📖 Membaca daftar bantuan."""
infoHelpMessage = """ℹ️ *Info*"""
infoYourLightningAddress = """Alamat Lightning mu adalah `%s`"""
basicsMessage = """🧡 *Bitcoin*
_Bitcoin adalah mata uang dari internet. Tidak memerlukan ijin dan terdesentralisasi dan tidak memiliki penguasa dan tidak ada otoritas yang mengatur. Bitcoin adalah uang yang tangguh yang lebih cepat, lebih aman, dan lebih inklusif dibanding sistem keuangan tradisional._
🧮 *Ekonomi*
_Unit terkecil dari Bitcoin adalah Satoshi (sat) dan 100,000,000 sat = 1 Bitcoin. Hanya akan pernah ada 21 Juta Bitcoin. Nilai Bitcoin dalam mata uang fiat dapat berubah tiap hari. Namun, jika kamu hidup dalam sebuah standar Bitcoin maka 1 sat akan selalu sama dengan 1 sat._
⚡️ *The Lightning Network*
_Lightning Network adalah sebuah protokol pembayaran yang memungkinkan pembayaran Bitcoin dengan cepat dan murah yang memerlukan hampir tidak ada energi. Ini lah yang membesarkan skala Bitcoin ke milyaran orang diseluruh dunia._
📲 *Lightning Wallets*
_Dana mu di bot ini dapat dikirim ke dompet Lightning manapun lainnya dan kebalikannya. Rekomendasi dompet Lightning untuk handphone mu adalah_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (non-custodial), or_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(easy)_.
📄 *Open Source*
_Bot ini gratis dan merupakan perangkat lunak_ [open source](https://github.com/LightningTipBot/LightningTipBot) _. Kamu dapat menjalankannya di komputer mu sendiri dan menggunakannya di komunitas mu._
✈️ *Telegram*
_Tambahkan bot ini ke percakapan grup Telegram mu untuk /tip postingan. Jika kamu membuat bot ini sebagai admin maka akan membersihkan perintah untuk agar percakapan tetap rapi._
🏛 *Persyaratan*
_Kami tidak menyimpan dana mu. Kami akan bertindak yang terbaik untuk kamu namun kami juga sadar bahwa situasi tanpa KYC agak sulit sampai kami bisa memikirkan sesuatu. Berapa pun jumlah yang kamu masukkan ke dompet mu akan dianggap sebagai donasi. Jangan kirim ke kami semua uang mu. Tolong sadar bahwa bot ini masih dalam perkembangan beta. Pergunakan lah dengan resiko mu sendiri._
❤️ *Donasi*
_Bot ini tidak memungut biaya tapi memerlukan Satoshi untuk bekerja. Kalau kamu menyukai bot ini, tolong pertimbangkan mendukung proyek ini dengan donasi. Untuk melakukan donasi, pakai_ `/donate 1000`"""
helpNoUsernameMessage = """👋 Silakan mengatur nama pengguna untuk Telegram."""
advancedMessage = """%s
👉 *Sebaris perintah*
*send* 💸 Kirim sats ke percakapan: `%s send <jumlah> [<berita>]`
*receive* 🏅 Permintaan pembayaran: `... receive <jumlah> [<berita>]`
*faucet* 🚰 Membuat sebuah keran: `... faucet <kapasitas> <per_pengguna>`
*tipjar* 🍯 Create a tipjar: `... tipjar <capacity> <per_user> [<memo>]`
📖 Kamu dapat menggunakan sebaris perintah di tiap percakapan, bahkan di percakapan privat. Tunggu sejenak setelah memasukkan sebaris perintah lalu *pencet* hasilnya, jangan tekan enter.
⚙️ *Perintah lanjutan*
*/link* 🔗 Menghubungkan dompet mu ke [BlueWallet](https://bluewallet.io/) atau [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Lnurl menerima atau membayar: `/lnurl` atau `/lnurl <lnurl>`
*/faucet* 🚰 Membuat sebuah keran `/faucet <kapasitas> <per_pengguna>`
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`"""
# GENERIC
enterAmountRangeMessage = """💯 Masukkan jumlah diantara %d dan %d sat."""
enterAmountMessage = """💯 Masukkan jumlah."""
enterUserMessage = """👤 Masukkan user."""
errorReasonMessage = """🚫 Error: %s"""
# START
startSettingWalletMessage = """🧮 Sedang menyiapkan dompet mu..."""
startWalletCreatedMessage = """🧮 Dompet sudah dibuat."""
startWalletReadyMessage = """✅ *Dompet mu sudah siap.*"""
startWalletErrorMessage = """🚫 Ada kesalahan dalam pembuatan dompet mu. Silakan coba lagi nanti."""
startNoUsernameMessage = """☝️ Kelihatannya kamu belum memiliki sebuah @username Telegram. Tidak apa-apa, kamu tidak memerlukan nya untuk menggunakan bot ini. Namun, agar dompet mu bisa lebih berguna, atur nama pengguna di pengaturan Telegram. Lalu, ketik /balance agar bot dapat memperbaharui catatan nya mengenai kamu."""
# BALANCE
balanceMessage = """👑 *Saldo mu:* %d sat"""
balanceErrorMessage = """🚫 Tidak dapat memeriksa saldo mu. Tolong coba lagi nanti."""
# TIP
tipDidYouReplyMessage = """Apakah kamu tadi membalas pesan untuk memberikan tip? Untuk membalas pesan mana pun, klik-kanan -> Ketik balasan pada komputer mu atau geser pesan yang ada di handphone mu. Jika kamu mau mengirimkan secara langsung, gunakan perintah /send ."""
tipInviteGroupMessage = """ℹ️ Ngomong-ngomong, kamu bisa mengundang bot ini ke grup mana saja untuk mulai memberikan tip disana."""
tipEnterAmountMessage = """Apakah kamu sudah memasukkan jumlah?"""
tipValidAmountMessage = """Apakah kamu memasukkan jumlah yang benar?"""
tipYourselfMessage = """📖 Kamu tidak dapat memberi tip ke diri sendiri."""
tipSentMessage = """💸 %d sat terkirim ke %s."""
tipReceivedMessage = """🏅 %s telah memberi tip sebanyak %d sat."""
tipErrorMessage = """🚫 Pengiriman tip gagal."""
tipUndefinedErrorMsg = """Silakan coba lagi nanti."""
tipHelpText = """📖 Waduh, itu tidak berhasil. %s
*Usage:* `/tip <jumlah> [<berita>]`
*Example:* `/tip 1000 Makasih!`"""
# SEND
sendValidAmountMessage = """Apakah kamu memasukkan jumlah yang benar?"""
sendUserHasNoWalletMessage = """🚫 Pengguna %s belum membuat dompet."""
sendSentMessage = """💸 %d sat terkirim ke %s."""
sendPublicSentMessage = """💸 %d sat terkirim dari %s ke %s."""
sendReceivedMessage = """🏅 %s mengirimkan kamu %d sat."""
sendErrorMessage = """🚫 Pengiriman gagal."""
confirmSendMessage = """Apakah kamu ingin membayar ke %s?\n\n💸 Jumlah: %d sat"""
confirmSendAppendMemo = """\n✉️ %s"""
sendCancelledMessage = """🚫 Pengiriman dibatalkan."""
errorTryLaterMessage = """🚫 Error. Silakan coba lagi nanti."""
sendSyntaxErrorMessage = """Apakah kamu sudah memasukkan jumlah dan penerima? Kamu dapat menggunakan perintah /send untuk ke pengguna Telegram seperti %s atau ke alamat Lightning seperti LightningTipBot@ln.tips."""
sendHelpText = """📖 Waduh, itu tidak berhasil. %s
*Usage:* `/send <jumlah> <pengguna> [<berita>]`
*Example:* `/send 1000 @LightningTipBot Gampang botnya dipakai ❤️`
*Example:* `/send 1234 LightningTipBot@ln.tips`"""
# INVOICE
invoiceReceivedMessage = """⚡️ Kamu menerima %d sat."""
invoiceEnterAmountMessage = """Apakah kamu sudah memasukkan jumlah?"""
invoiceValidAmountMessage = """Apakah kamu memasukkan jumlah yang benar?"""
invoiceHelpText = """📖 Waduh, itu tidak berhasil. %s
*Usage:* `/invoice <jumlah> [<berita>]`
*Example:* `/invoice 1000 Makasih!`"""
# PAY
paymentCancelledMessage = """🚫 Pembayaran dibatalkan."""
invoicePaidMessage = """⚡️ Pembayaran terkirim."""
invoicePublicPaidMessage = """⚡️ Pembayaran dikirim oleh %s."""
invalidInvoiceHelpMessage = """Apakah kamu memasukan invoice Lightning yang benar? Coba /send jika kamu mau mengirimkan ke pengguna Telegram atau alamat Lightning."""
invoiceNoAmountMessage = """🚫 Tidak dapat membayar invoice tanpa jumlah."""
insufficientFundsMessage = """🚫 Kekurangan dana. Kamu memiliki %d sat namun kamu memerlukan setidaknya %d sat."""
feeReserveMessage = """⚠️ Mengirimkan seluruh saldo bisa gagal karena adanya biaya jaringan. Jika gagal, coba jumlah kirimnya dikurangi sedikit."""
invoicePaymentFailedMessage = """🚫 Pembayaran gagal: %s"""
invoiceUndefinedErrorMessage = """Tidak dapat membayar invoice."""
confirmPayInvoiceMessage = """Apakah kamu mau mengirimkan pembayaran ini?\n\n💸 Jumlah: %d sat"""
confirmPayAppendMemo = """\n✉️ %s"""
payHelpText = """📖 Waduh, itu tidak berhasil. %s
*Usage:* `/pay <invoice>`
*Example:* `/pay lnbc20n1psscehd...`"""
# DONATE
donationSuccess = """🙏 Terima kasih untuk donasi mu."""
donationErrorMessage = """🚫 Waduh. Donasi gagal."""
donationProgressMessage = """🧮 Menyiapkan donasi mu..."""
donationFailedMessage = """🚫 Donasi gagal: %s"""
donateEnterAmountMessage = """Apakah kamu sudah memasukkan jumlah?"""
donateValidAmountMessage = """Apakah kamu memasukkan jumlah yang benar?"""
donateHelpText = """📖 Waduh, itu tidak berhasil. %s
*Usage:* `/donate <jumlah>`
*Example:* `/donate 1000`"""
# PHOTO
photoQrNotRecognizedMessage = """🚫 Tidak dapat mengenali sebuah invoice Lightning invoice atau sebuah LNURL. Coba arahkan ke tengah QR code, potong foto kodenya, atau zoom in."""
photoQrRecognizedMessage = """✅ QR code:
`%s`"""
# LNURL
lnurlReceiveInfoText = """👇 Kamu dapat menggunakan LNURL statis ini untuk menerima pembayaran."""
lnurlResolvingUrlMessage = """🧮 Menyelesaikan alamat..."""
lnurlGettingUserMessage = """🧮 Mempersiapkan pembayaran..."""
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."""
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*
⚠️ Jangan pernah membagikan URL atau kode QR nya dengan siapa pun karena mereka akan bisa mengakses dana mu.
- *BlueWallet:* Tekan *New wallet*, *Import wallet*, *Scan atau import a file*, lalu scan kode QR nya.
- *Zeus:* Salin URL dibawah, tekan *Add a new node*, *Import* (URL nya), *Save Node Config*."""
couldNotLinkMessage = """🚫 Tidak dapat menghubungkan dompet mu. Silakan coba lagi nanti."""
# FAUCET
inlineQueryFaucetTitle = """🚰 Membuat sebuah keran."""
inlineQueryFaucetDescription = """Penggunaan: @%s faucet <kapasitas> <per_pengguna>"""
inlineResultFaucetTitle = """🚰 Buat sebuah keran %d sat."""
inlineResultFaucetDescription = """👉 Pencet disini untuk membuat sebuah keran di percakapan ini."""
inlineFaucetMessage = """Tekan ✅ untuk mengambil %d sat dari keran ini.
🚰 Tersisa: %d/%d sat (diberikan kepada %d/%d pengguna)
%s"""
inlineFaucetEndedMessage = """🚰 Keran kosong 🍺\n\n🏅 %d sat diberikan kepada %d pengguna."""
inlineFaucetAppendMemo = """\n✉️ %s"""
inlineFaucetCreateWalletMessage = """Bercakap dengan %s 👈 untuk mengelola dompet mu."""
inlineFaucetCancelledMessage = """🚫 Keran dibatalkan."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Jumlah untuk tiap pengguna tidak terbagi dari kapasitas."""
inlineFaucetInvalidAmountMessage = """🚫 Jumlah tidak benar."""
inlineFaucetSentMessage = """🚰 %d sat terkirim ke %s."""
inlineFaucetReceivedMessage = """🚰 %s mengirimkan kamu %d sat."""
inlineFaucetHelpFaucetInGroup = """Buat sebuah keran dalam sebuah grup dengan bot nya didalam atau gunakan 👉 perintah sebaris (/advanced untuk lebih lagi)."""
inlineFaucetHelpText = """📖 Waduh, itu tidak berhasil. %s
*Usage:* `/faucet <kapasitas> <per_pengguna>`
*Example:* `/faucet 210 21`"""
# INLINE SEND
inlineQuerySendTitle = """💸 Kirimkan pembayaran ke sebuah percakapan."""
inlineQuerySendDescription = """Penggunaan: @%s send <jumlah> [<pengguna>] [<berita>]"""
inlineResultSendTitle = """💸 Kirim %d sat."""
inlineResultSendDescription = """👉 Pencet untuk mengirim %d sat ke percakapan ini."""
inlineSendMessage = """Tekan ✅ untuk menerima pembayaran dari %s.\n\n💸 Jumlah: %d sat"""
inlineSendAppendMemo = """\n✉️ %s"""
inlineSendUpdateMessageAccept = """💸 %d sat terkirim dari %s ke %s."""
inlineSendCreateWalletMessage = """Bercakap dengan %s 👈 untuk mengelola dompet mu."""
sendYourselfMessage = """📖 Kamu tidak dapat membayar diri mu sendiri."""
inlineSendFailedMessage = """🚫 Pengiriman tidak berhasil."""
inlineSendInvalidAmountMessage = """🚫 Jumlah harus lebih besar dari 0."""
inlineSendBalanceLowMessage = """🚫 Saldo mu terlalu rendah."""
# INLINE RECEIVE
inlineQueryReceiveTitle = """🏅 Meminta pembayaran dalam sebuah percakapan."""
inlineQueryReceiveDescription = """Penggunaan: @%s receive <jumlah> [<pengguna>] [<berita>]"""
inlineResultReceiveTitle = """🏅 Menerima %d sat."""
inlineResultReceiveDescription = """👉 Pencet untuk permintaan pembayaran sebesar %d sat."""
inlineReceiveMessage = """Tekan 💸 untuk membayar ke %s.\n\n💸 Jumlah: %d sat"""
inlineReceiveAppendMemo = """\n✉️ %s"""
inlineReceiveUpdateMessageAccept = """💸 %d sat terkirim oleh %s ke %s."""
inlineReceiveCreateWalletMessage = """Bercakap dengan %s 👈 untuk mengelola dompet mu."""
inlineReceiveYourselfMessage = """📖 Kamu tidak dapat membayar diri mu sendiri."""
inlineReceiveFailedMessage = """🚫 Penerimaan gagal."""
inlineReceiveCancelledMessage = """🚫 Penerimaan dibatalkan."""
+22 -15
View File
@@ -68,10 +68,10 @@ _Questo bot non applica commissioni agli utenti, ma costa alcuni Satoshi gestirl
%s
⚙️ *Comandi*
*/tip* 🏅 Rispondi così a un messaggio per inviare una mancia: `/tip <ammontare> [<descrizione>]`
*/tip* 🏅 Rispondi così a un messaggio per inviare una mancia: `/tip <ammontare> [<memo>]`
*/balance* 👑 Verifica il tuo saldo residuo: `/balance`
*/send* 💸 Invia fondi a un utente: `/send <ammontare> @utente o utente@ln.tips [<descrizione>]`
*/invoice* ⚡️ Ricevi attraverso Lightning: `/invoice <ammontare> [<descrizione>]`
*/send* 💸 Invia fondi a un utente: `/send <ammontare> @utente o utente@ln.tips [<memo>]`
*/invoice* ⚡️ Ricevi attraverso Lightning: `/invoice <ammontare> [<memo>]`
*/pay* ⚡️ Paga attraverso Lightning: `/pay <invoice>`
*/donate* ❤️ Dona per supportare questo progetto: `/donate 1000`
*/advanced* 🤖 Funzioni avanzate.
@@ -109,16 +109,24 @@ helpNoUsernameMessage = """👋 Per favore imposta un nome utente Telegram."""
advancedMessage = """%s
👉 *Comandi in linea*
*send* 💸 Invia alcuni sat a una chat: `%s send <ammontare> [<descrizione>]`
*receive* 🏅 Richiedi un pagamento: `%s receive <ammontare> [<descrizione>]`
*faucet* 🚰 Eroga fondi ai partecipanti della chat: `%s faucet <ammontare_totale> <per_utente>`
*send* 💸 Invia alcuni sat a una chat: `%s send <ammontare> [<utente>] [<memo>]`
*receive* 🏅 Richiedi un pagamento: `... receive <ammontare> [<utente>] [<memo>]`
*faucet* 🚰 Crea una distribuzione: `... faucet <totale> <per_utente> [<memo>]`
*tipjar* 🍯 Crea un tipjar: `... tipjar <totale> <per_utente> [<memo>]`
📖 Puoi usare i comandi in linea in ogni chat, anche nelle conversazioni private. Attendi un secondo dopo aver inviato un comando in linea e *clicca* sull'azione desiderata, non premere invio.
⚙️ *Comandi avanzati*
*/link* 🔗 Crea un collegamento al tuo wallet [BlueWallet](https://bluewallet.io/) o [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Ricevi o paga un Lnurl: `/lnurl` or `/lnurl <lnurl>`
*/faucet* 🚰 Eroga fondi ai partecipanti della chat `/faucet <ammontare_totale> <per_utente>`"""
*/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
@@ -146,7 +154,7 @@ tipErrorMessage = """🚫 Invio mancia non riuscito."""
tipUndefinedErrorMsg = """Per favore riprova più tardi."""
tipHelpText = """📖 Ops, non funziona. %s
*Usage:* `/tip <ammontare> [<descrizione>]`
*Usage:* `/tip <ammontare> [<memo>]`
*Example:* `/tip 1000 meme fantastico!`"""
# SEND
@@ -164,7 +172,7 @@ errorTryLaterMessage = """🚫 Errore. Per favore riprova più tardi."""
sendSyntaxErrorMessage = """Hai specificato un ammontare e un destinatario? Puoi usare il comando /send per inviare sia a utenti Telegram come %s sia a un indirizzo Lightning del tipo LightningTipBot@ln.tips."""
sendHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/send <ammontare> <utente> [<descrizione>]`
*Sintassi:* `/send <ammontare> <utente> [<memo>]`
*Esempio:* `/send 1000 @LightningTipBot Amo questo bot ❤️`
*Esempio:* `/send 1234 LightningTipBot@ln.tips`"""
@@ -175,7 +183,7 @@ invoiceEnterAmountMessage = """Hai inserito un ammontare?"""
invoiceValidAmountMessage = """Hai inserito un ammontare valido?"""
invoiceHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/invoice <ammontare> [<descrizione>]`
*Sintassi:* `/invoice <ammontare> [<memo>]`
*Esempio:* `/invoice 1000 Grazie!`"""
# PAY
@@ -224,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."""
lnurlEnterAmountMessage = """⌨️ Imposta un ammontare tra %d e %d sat."""
lnurlHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/lnurl [ammontare] <lnurl>`
@@ -243,7 +250,7 @@ couldNotLinkMessage = """🚫 Non sono riuscito a collegare il tuo wallet. Per f
# FAUCET
inlineQueryFaucetTitle = """🚰 Crea una distribuzione di fondi."""
inlineQueryFaucetDescription = """Sintassi: @%s faucet <ammontare_totale> <per_utente>"""
inlineQueryFaucetDescription = """Sintassi: @%s faucet <totale> <per_utente>"""
inlineResultFaucetTitle = """🚰 Crea una distribuzione per un totale di %d sat."""
inlineResultFaucetDescription = """👉 Clicca qui per creare una distribuzione di fondi in questa chat."""
@@ -262,13 +269,13 @@ inlineFaucetReceivedMessage = """🚰 %s ti ha inviato %d sat."""
inlineFaucetHelpFaucetInGroup = """Crea una distribuzione in un gruppo in cui sia presente il bot oppure usa il 👉 comando in linea (/advanced per ulteriori funzionalità)."""
inlineFaucetHelpText = """📖 Ops, non ha funzionato. %s
*Sintassi:* `/faucet <ammontare_totale> <per_utente>`
*Sintassi:* `/faucet <totale> <per_utente>`
*Esempio:* `/faucet 210 21`"""
# INLINE SEND
inlineQuerySendTitle = """💸 Invia pagamento in una chat."""
inlineQuerySendDescription = """Sintassi: @%s send <ammontare> [<descrizione>]"""
inlineQuerySendDescription = """Sintassi: @%s send <ammontare> [<utente>] [<memo>]"""
inlineResultSendTitle = """💸 Invio %d sat."""
inlineResultSendDescription = """👉 Clicca per inviare %d sat in questa chat."""
@@ -284,7 +291,7 @@ inlineSendBalanceLowMessage = """🚫 Il tuo saldo è insufficiente (%d sat).
# INLINE RECEIVE
inlineQueryReceiveTitle = """🏅 Richiedi un pagamento in una chat."""
inlineQueryReceiveDescription = """Sintassi: @%s receive <ammontare> [<descrizione>]"""
inlineQueryReceiveDescription = """Sintassi: @%s receive <ammontare> [<utente>] [<memo>]"""
inlineResultReceiveTitle = """🏅 Ricevi %d sat."""
inlineResultReceiveDescription = """👉 Clicca per richiedere un pagamento di %d sat."""
+22 -7
View File
@@ -109,16 +109,24 @@ helpNoUsernameMessage = """👋 Stel alstublieft een Telegram gebruikersnaam in.
advancedMessage = """%s
👉 *Inline commands*
*send* 💸 Stuur sats naar chat: `%s send <bedrag> [<memo>]`
*receive* 🏅 Verzoek om betaling: `%s receive <bedrag> [<memo>]`
*faucet* 🚰 Maak een kraan: `%s faucet <capacity> <per_user>`
*send* 💸 Stuur sats naar chat: `%s send <bedrag> [<user>] [<memo>]`
*receive* 🏅 Verzoek om betaling: `... receive <bedrag> [<user>] [<memo>]`
*faucet* 🚰 Maak een kraan: `... faucet <capacity> <per_user> [<memo>]`
*tipjar* 🍯 Maak een tipjar: `... tipjar <capacity> <per_user> [<memo>]`
📖 Je kunt inline commando's in elke chat gebruiken, zelfs in privé gesprekken. Wacht een seconde na het invoeren van een inline commando en *klik* op het resultaat, druk niet op enter.
⚙️ *Geavanceerde opdrachten*
*/link* 🔗 Koppel uw wallet aan [BlueWallet](https://bluewallet.io/) of [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Lnurl ontvangen of betalen: `/lnurl` of `/lnurl <lnurl>`
*/faucet* 🚰 Maak een kraan `/faucet <capacity> <per_user>`"""
*/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
@@ -224,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."""
lnurlEnterAmountMessage = """⌨️ 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*
@@ -268,7 +283,7 @@ inlineFaucetHelpText = """📖 Oeps, dat werkte niet. %s
# INLINE VERZENDEN
inlineQuerySendTitle = """💸 Stuur betaling naar een chat."""
inlineQuerySendDescription = """Gebruik: @%s send <bedrag> [<memo>]"""
inlineQuerySendDescription = """Gebruik: @%s send <bedrag> [<user>] [<memo>]"""
inlineResultSendTitle = """💸 Stuur %d sat."""
inlineResultSendDescription = """👉 Klik om %d sat naar deze chat te sturen."""
@@ -284,7 +299,7 @@ inlineSendBalanceLowMessage = """🚫 Uw saldo is te laag."""
# INLINE RECEIVE
inlineQueryReceiveTitle = """🏅 Vraag een betaling in een chat."""
inlineQueryReceiveDescription = """Gebruik: @%s receive <bedrag> [<memo>]"""
inlineQueryReceiveDescription = """Gebruik: @%s receive <bedrag> [<user>] [<memo>]"""
inlineResultReceiveTitle = """🏅 Ontvang %d sat."""
inlineResultReceiveDescription = """👉 Klik om een betaling van %d sat aan te vragen."""
+46 -7
View File
@@ -109,16 +109,24 @@ helpNoUsernameMessage = """👋 Por favor, digite um nome de usuário do Telegra
advancedMessage = """%s
👉 *Comandos Inline*
*send* 💸 Enviar sats ao bate-papo: `%s send <quantidade> [<memo>]`
*receive* 🏅 Solicite um pagamento: `%s receive <quantidade> [<memo>]`.
*faucet* 🚰 Criar uma torneira: `%s faucet <capacidade> <por_usuário>`.
*send* 💸 Enviar sats ao bate-papo: `%s send <quantidade> [<usuário>] [<memo>]`
*receive* 🏅 Solicite um pagamento: `... receive <quantidade> [<usuário>] [<memo>]`
*faucet* 🚰 Criar uma torneira: `... faucet <capacidade> <por_usuário> [<memo>]`
*tipjar* 🍯 Criar uma tipjar: `... tipjar <capacidade> <por_usuário> [<memo>]`
📖 Você pode usar comandos _inline_ em todas as conversas, mesmo em conversas privadas. Espere um segundo após inserir um comando _inline_ e *clique* no resultado, não pressione enter.
⚙️ *Comandos avançados*
*/link* 🔗 Vincule sua carteira a [ BlueWallet ](https://bluewallet.io/) ou [ Zeus ](https://zeusln.app/)
*/lnurl* ⚡️ Receber ou pagar com lnurl: `/lnurl` o `/lnurl <lnurl>`
*/faucet* 🚰 Criar uma torneira: `%s faucet <capacidade> <por_usuário>`"""
*/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
@@ -224,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."""
lnurlEnterAmountMessage = """⌨️ 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*
@@ -268,7 +283,7 @@ inlineFaucetHelpText = """📖 Opa, isso não funcionou. %s
# INLINE SEND
inlineQuerySendTitle = """💸 Enviar pagamento para um bate-papo."""
inlineQuerySendDescription = """Uso: @%s send <quantia> [<memo>]"""
inlineQuerySendDescription = """Uso: @%s send <quantia> [<usuário>] [<memo>]"""
inlineResultSendTitle = """💸 Enviar %d sat."""
inlineResultSendDescription = """👉 Clique para enviar %d sat neste bate-papo."""
@@ -284,7 +299,7 @@ inlineSendBalanceLowMessage = """🚫 Seu saldo é muito baixo."""
# INLINE RECEIVE
inlineQueryReceiveTitle = """🏅 Solicite um pagamento em um bate-papo."""
inlineQueryReceiveDescription = """Uso: @%s receive <quantidade> [<memo>]"""
inlineQueryReceiveDescription = """Uso: @%s receive <quantidade> [<usuário>] [<memo>]"""
inlineResultReceiveTitle = """🏅 Receber %d sat."""
inlineResultReceiveDescription = """👉 Clique para solicitar um pagamento de %d sat."""
@@ -295,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`"""
+304
View File
@@ -0,0 +1,304 @@
# COMMANDS
helpCommandStr = """yardım"""
basicsCommandStr = """temelbilgi"""
tipCommandStr = """bahşiş"""
balanceCommandStr = """kredi"""
sendCommandStr = """gönder"""
invoiceCommandStr = """fatura"""
payCommandStr = """öde"""
donateCommandStr = """bağış"""
advancedCommandStr = """gelişmiş"""
transactionsCommandStr = """işlemler"""
logCommandStr = """kayıt"""
listCommandStr = """liste"""
linkCommandStr = """bağlan"""
lnurlCommandStr = """lnurl"""
faucetCommandStr = """fıçı"""
tipjarCommandStr = """bağışkutusu"""
receiveCommandStr = """iste"""
hideCommandStr = """sakla"""
volcanoCommandStr = """volkan"""
showCommandStr = """göster"""
optionsCommandStr = """seçenekler"""
settingsCommandStr = """ayarlar"""
saveCommandStr = """kaydet"""
deleteCommandStr = """sil"""
infoCommandStr = """info"""
# NOTIFICATIONS
cantDoThatMessage = """Bunu yapamazsın."""
cantClickMessage = """Bu butona basamazsın."""
balanceTooLowMessage = """Kredin yetersiz."""
# BUTTONS
sendButtonMessage = """✅ Gönder"""
payButtonMessage = """✅ Öde"""
payReceiveButtonMessage = """💸 Öde"""
receiveButtonMessage = """✅ İste"""
cancelButtonMessage = """🚫 İptal"""
collectButtonMessage = """✅ Topla"""
nextButtonMessage = """İleri"""
backButtonMessage = """Geri"""
acceptButtonMessage = """Onayla"""
denyButtonMessage = """Reddet"""
tipButtonMessage = """Bahşiş"""
revealButtonMessage = """Göster"""
showButtonMessage = """Göster"""
hideButtonMessage = """Sakla"""
joinButtonMessage = """Katıl"""
optionsButtonMessage = """Seçenekler"""
settingsButtonMessage = """Ayarlar"""
saveButtonMessage = """Kaydet"""
deleteButtonMessage = """Sil"""
infoButtonMessage = """Info"""
# HELP
helpMessage = """⚡️ *Cüzdan*
_Bitcoin Lightning Cüzdan botu ile Telegram üzerinden bahşiş gönderebilirsin. Bahşiş göndermek için botu bir grup sohbetine ekle. Temel bahşiş birimi Satoshi’dir (sat). 100,000,000 sat = 1 Bitcoin. Daha fazla bilgi için 📚 /basics gir._
❤️ *Bağış yap*
_Bu bot ücretsizdir, ancak çalıştırılması için Satoshi gerekir. Botu beğendiysen bağış yaparak projeye destek olabilirsin. Bağış yapmak için şunu gir: _ `/donate 1000`
%s
⚙️ *Komutlar*
*/tip* 🏅 Bağış yapmak için mesajı cevapla: `/tip <miktar> [<bildirim>]`
*/balance* 👑 Kredini sorgula: `/balance`
*/send* 💸 Bir kullanıcıya gönder: `/send <miktar> @user veya user@ln.tips [<bildirim>]`
*/invoice* ⚡️ Lightning ile iste: `/invoice <miktar> [<bildirim>]`
*/pay* ⚡️ Lightning ile öde: `/pay <invoice>`
*/donate* ❤️ Projeye bağış yap: `/donate 1000`
*/advanced* 🤖 Gelişmiş fonksiyonlar.
*/help* 📖 Yardım."""
infoHelpMessage = """ℹ️ *Info*"""
infoYourLightningAddress = """Lightning adresin `%s`"""
basicsMessage = """🧡 *Bitcoin*
_Bitcoin internetin para birimidir. Herkese açık, merkezi olmayan, kontrol edeni olmayan, klasik finansal sistemden daha hızlı, daha güvenli ve daha adil olan sağlam bir paradır._
🧮 *Ekonomi*
_En küçük Bitcoin birimi Satoshi’dir (sat). 100.000.000 sat = 1 Bitcoin. Asla 21 milyondan fazla Bitcoin üretilmeyecek. Bitcoin'in itibari para değeri günlük olarak değişebilir. Ancak Bitcoin Standardı kullanıyorsan, 1 sat sonsuza kadar 1 sat değerinde olacaktır._
⚡️ *Lightning Network*
_Lightning Network neredeyse hiç enerji gerektirmeyen hızlı ve ucuz Bitcoin ödemelerine izin veren bir protokolüdür. Böylece Bitcoin dünya çapında milyarlarca insana ulaşır._
📲 *Lightning Cüzdanlar*
_Bu bottaki paranı dünyadaki herhangi bir Lightning cüzdanına gönderebilirsin. Cep telefonunun için önerilen Lightning cüzdanları şunlardır:_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (emanet edilmeyen), veya_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(kolay)_.
📄 *Açık Kaynak*
_Bu bot ücretsiz ve_ [açık kaynak](https://github.com/LightningTipBot/LightningTipBot) _yazılım. Kendi bilgisayarında çalıştırabilir ve topluluğun için kullanabilirsin._
✈️ *Telegram*
_/tip göndermek için botu Telegram grubunuza ekle. Bot grubun yöneticisiyse, yürütmeden sonra bazı komutları silerek sohbeti de temizleyecektir._
🏛 *Kullanım Şartları*
_Biz senin paranın emanetçisi değiliz. Senin faydanı gözetiyoruz. Ancak KYC'siz durumun biraz karmaşık olduğunun da farkındayız. Başka bir çözüm bulana kadar bu bottaki tüm tutarları bağış olarak kabul ediyoruz. Tüm paranı bize verme. Bu botun hala beta aşamasında olduğunu unutma. Kullanımın senin sorumluluğundadır._
❤️ *Bağış yap*
_Bu bot ücretsizdir, ancak çalıştırılması için Satoshi gerekir. Botu beğendiysen bağış yaparak projeye destek olabilirsin. Bağış yapmak için şunu gir:_ `/donate 1000`"""
helpNoUsernameMessage = """👋 Ayarlarda bir Telegram kullanıcı adı seç."""
advancedMessage = """%s
👉 *Inline komutlar*
*send* 💸 Bir sohbete sat gönder: `%s send <miktar> [<kullanıcı>] [<bildirim>]`
*receive* 🏅 Ödeme iste: `%s receive <miktar> [<kullanıcı>] [<bildirim>]`
*faucet* 🚰 Bir fıçı oluştur: `%s faucet <toplam> <kullanıcı_başına> [<bildirim>]`
*tipjar* 🍯 Bir tipjar oluştur: `... tipjar <toplam> <kullanıcı_başına> [<bildirim>]`
📖 İnline komutları her sohbette ve hatta özel mesajlarda kullanabilirsin. Komutu yazdıktan sonra bir saniye bekle ve Enter yazmak yerine sonuca *tıkla*.
⚙️ *Gelişmiş komutlar*
*/link* 🔗 Cüzdanını bağla: [BlueWallet](https://bluewallet.io/) veya [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Lnurl iste veya gönder: `/lnurl` veya `/lnurl <lnurl>`
*/faucet* 🚰 Bir fıçı oluştur: `/faucet <toplam> <kullanıcı_başına>`
*/tipjar* 🍯 Bir tipjar oluştur: `/tipjar <capacity> <per_user>`"""
# 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…"""
startWalletCreatedMessage = """🧮 Cüzdanın hazır."""
startWalletReadyMessage = """✅ *Cüzdanın hazır.*"""
startWalletErrorMessage = """🚫 Cüzdanın hazırlanırken bir hata oluştu. Lütfen daha sonra tekrar dene."""
startNoUsernameMessage = """☝️ Henüz bir Telegram kullanıcı @adın yok gibi görünüyor. Sorun değil, bu botu kullanmak için kullanıcı adına ihtiyacın yok. Ancak tüm fonksiyonları kullanabilmek için Telegram ayarlarında bir kullanıcı adı belirlemelisin. Ardından botun seninle ilgili bilgilerini güncelleyebilmesi için bir kez /balance gir."""
# BALANCE
balanceMessage = """👑 *Kredin:* %d sat"""
balanceErrorMessage = """🚫 Şu an kredini okuyamıyorum. Lütfen daha sonra tekrar dene."""
# TIP
tipDidYouReplyMessage = """Birine bahşiş göndermek için bir mesajı yanıtladın mı? Yanıtlamak için bilgisayarında mesaja sağ tıklayarak Yanıtla. Telefonda ise mesajı kaydır. Ödemeyi doğrudan başka bir kullanıcıya göndermek istiyorsan /send komutunu kullan."""
tipInviteGroupMessage = """ℹ️ Bu arada, bu botu herhangi bir grup sohbetine davet edebilir ve orada bahşiş dağıtabilirsin."""
tipEnterAmountMessage = """Miktar girdin mi?"""
tipValidAmountMessage = """Geçerli bir miktar girdin mi?"""
tipYourselfMessage = """📖 Kendi kendine bahşiş gönderemezsin."""
tipSentMessage = """💸 %d sat %s a gönderildi."""
tipReceivedMessage = """🏅 %s sana %d sat bahşiş gönderdi."""
tipErrorMessage = """🚫 Bahşiş gönderilemedi."""
tipUndefinedErrorMsg = """lütfen daha sonra tekrar dene."""
tipHelpText = """📖 Hoppalaa… olmadı. %s
*Komut:* `/tip <miktar> [<bildirim>]`
*Örnek:* `/tip 1000 Çok iyi yaa!`"""
# SEND
sendValidAmountMessage = """Geçerli bir miktar girdin mi?"""
sendUserHasNoWalletMessage = """🚫 %s henüz bir cüzdan oluşturmadı."""
sendSentMessage = """💸 %d sat %s a gönderildi."""
sendPublicSentMessage = """💸 %d sat %s dan %s a gönderildi."""
sendReceivedMessage = """🏅 %s sana %d sat gönderdi."""
sendErrorMessage = """🚫 Gönderim başarılı olmadı."""
confirmSendMessage = """%s a ödeme göndermek istiyor musun?\n\n💸 Miktar: %d sat"""
confirmSendAppendMemo = """\n✉️ %s"""
sendCancelledMessage = """🚫 Gönderim iptal edildi."""
errorTryLaterMessage = """🚫 Hata. Lütfen daha sonra tekrar dene."""
sendSyntaxErrorMessage = """Geçerli bir miktar ve kullanıcı girdin mi? /send komutu ile bir Telegram kullanıcısına, örnek %s, veya bir Lightning adrese, örnek LightningTipBot@ln.tips, gönderilebilir."""
sendHelpText = """📖 Hoppalaa… olmadı. %s
*Komut:* `/send <miktar> <kullanıcı> [<bildirim>]`
*Örnek:* `/send 1000 @LightningTipBot Bot harika kanka! ❤️`
*Örnek:* `/send 1234 LightningTipBot@ln.tips`"""
# INVOICE
invoiceReceivedMessage = """⚡️ %d sat sana geldi."""
invoiceEnterAmountMessage = """Miktar girdin mi?"""
invoiceValidAmountMessage = """Geçerli bir miktar girdin mi?"""
invoiceHelpText = """📖 Hoppalaa… olmadı. %s
*Komut:* `/invoice <miktar> [<bildirim>]`
*Örnek:* `/invoice 1000 Şimdiden teşekkürler!`"""
# PAY
paymentCancelledMessage = """🚫 Ödeme iptal edildi."""
invoicePaidMessage = """⚡️ Ödeme gönderildi."""
invoicePublicPaidMessage = """⚡️ %s ödeme gönderdi."""
invalidInvoiceHelpMessage = """Geçerli bir Lightning Invoice girdin mi? Telegram kullanıcısına veya Lightning adrese ödeme yapmak için /send komutunu kullan."""
invoiceNoAmountMessage = """🚫 Miktar belirtilmemiş Invoice ödenemez."""
insufficientFundsMessage = """🚫 Kredin yetersiz. Şu an cüzdanında %d sat var. Ancak en az %d sat gerekiyor."""
feeReserveMessage = """⚠️ Cüzdanındaki tüm miktarı göndermek istiyorsun. Ancak Lightning ücreti ödenemeyeceği için gönderim başarısız olabilir. Bu durumda daha az bir miktar dene."""
invoicePaymentFailedMessage = """🚫 Ödeme başarısız: %s"""
invoiceUndefinedErrorMessage = """Invoice ödenemedi."""
confirmPayInvoiceMessage = """Bu ödemeyi göndermek istiyor musun?\n\n💸 Miktar: %d sat"""
confirmPayAppendMemo = """\n✉️ %s"""
payHelpText = """📖 Hoppalaa… olmadı. %s
*Komut:* `/pay <invoice>`
*Örnek:* `/pay lnbc20n1psscehd...`"""
# DONATE
donationSuccess = """🙏 Bağış için teşekkürler."""
donationErrorMessage = """🚫 Bağış yapılamadı."""
donationProgressMessage = """🧮 Bağışın hazırlanıyor…"""
donationFailedMessage = """🚫 Bağış yapılamadı: %s"""
donateEnterAmountMessage = """Miktar girdin mi?"""
donateValidAmountMessage = """Geçerli bir miktar girdin mi?"""
donateHelpText = """📖 Hoppalaa… olmadı. %s
*Komut:* `/donate <miktar>`
*Örnek:* `/donate 1000`"""
# PHOTO
photoQrNotRecognizedMessage = """🚫 Lightning Invoice veya LNURL tanımlanamadı. QR Kodunu ortalayarak, boyutlandırarak veya büyüterek tekrar dene."""
photoQrRecognizedMessage = """✅ QR Code:
`%s`"""
# LNURL
lnurlReceiveInfoText = """👇 Bu LNURL kodunu ödeme almak için kullanabilirsin."""
lnurlResolvingUrlMessage = """🧮 Adres çözümleniyor…"""
lnurlGettingUserMessage = """🧮 Ödeme hazırlanıyor..."""
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."""
lnurlHelpText = """📖 Hoppalaa… olmadı. %s
*Komut:* `/lnurl [miktar] <lnurl>`
*Örnek:* `/lnurl LNURL1DP68GUR...`"""
# LINK
walletConnectMessage = """🔗 *Cüzdanını bağla*
⚠️ Bu URL yi veya QR kodunu kimseyle paylaşma. Bu bilgiye ulaşan biri hesabına da ulaşabilir.
- *BlueWallet:* *New wallet*, *Import wallet*, *Scan or import a file* tıkla ve QR kodunu tarat.
- *Zeus:* Aşağıdaki URL’yi kopyala ve *Add a new node*, *Import* (URL’yi), *Save Node Config* tıkla."""
couldNotLinkMessage = """🚫 Cüzdanın bağlanamadı. Lütfen daha sonra tekrar dene."""
# FAUCET
inlineQueryFaucetTitle = """🚰 Bir Fıçı oluştur."""
inlineQueryFaucetDescription = """Komut: @%s faucet <toplam> <kullanıcı_başına>"""
inlineResultFaucetTitle = """🚰 Bir %d sat Fıçı oluştur."""
inlineResultFaucetDescription = """👉 Fıçı’yı bu sohbete göndermek için tıkla."""
inlineFaucetMessage = """✅ butonuna basarak Fıçıdan %d sat çek.
🚰 Kalan: %d/%d sat (%d/%d çekildi)
%s"""
inlineFaucetEndedMessage = """🚰 Fıçı boşaldı 🍺\n\n🏅 %d sat %d kullanıcıya dağıtıldı."""
inlineFaucetAppendMemo = """\n✉️ %s"""
inlineFaucetCreateWalletMessage = """%s 👈 ile cüzdanı kullanmak için sohbete başla."""
inlineFaucetCancelledMessage = """🚫 Fıçı iptal edildi."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Toplam miktar bölü kullanıcı başına miktar tam sayı olmalı. Bu sayı küsuratlı olmaz."""
inlineFaucetInvalidAmountMessage = """🚫 Geçersiz miktar."""
inlineFaucetSentMessage = """🚰 %d sat %s a gönderildi."""
inlineFaucetReceivedMessage = """🚰 %s sana %d sat gönderdi."""
inlineFaucetHelpFaucetInGroup = """Fıçıyı İçinde bot olan bir grupta oluştur veya 👉 Inline komutunu kullan (/advanced daha fazla bilgi)."""
inlineFaucetHelpText = """📖 Hoppalaa… olmadı. %s
*Komut:* `/faucet <toplam> <kullanıcı_başına>`
*Örnek:* `/faucet 210 21`"""
# INLINE SEND
inlineQuerySendTitle = """💸 Sohbete ödeme gönder."""
inlineQuerySendDescription = """Komut: @%s send <miktar> [<kullanıcı>] [<bildirim>]"""
inlineResultSendTitle = """💸 %d sat gönder."""
inlineResultSendDescription = """👉 Sohbete %d sat göndermek için tıkla."""
inlineSendMessage = """✅ Butona basarak %s dan ödeme al.\n\n💸 Miktar: %d sat"""
inlineSendAppendMemo = """\n✉️ %s"""
inlineSendUpdateMessageAccept = """💸 %d sat %s dan %s ye gönderildi."""
inlineSendCreateWalletMessage = """%s 👈 ile cüzdanı kullanmak için sohbete başla."""
sendYourselfMessage = """📖 Kendi kendine ödeme yapamazsın."""
inlineSendFailedMessage = """🚫 Gönderim başarısız."""
inlineSendInvalidAmountMessage = """🚫 Miktar 0 dan büyük olmalı."""
inlineSendBalanceLowMessage = """🚫 Kredin yetersiz."""
# INLINE RECEIVE
inlineQueryReceiveTitle = """🏅 Sohbetten ödeme iste."""
inlineQueryReceiveDescription = """Komut: @%s receive <miktar> [<kullanıcı>] [<bildirim>]"""
inlineResultReceiveTitle = """🏅 %d sat iste."""
inlineResultReceiveDescription = """👉%d sat istemek için tıkla."""
inlineReceiveMessage = """💸 butonuna basarak %s a öde.\n\n💸 Miktar: %d sat"""
inlineReceiveAppendMemo = """\n✉️ %s"""
inlineReceiveUpdateMessageAccept = """💸 %d sat %s dan %s ye gönderildi."""
inlineReceiveCreateWalletMessage = """%s 👈 ile cüzdanı kullanmak için sohbete başla."""
inlineReceiveYourselfMessage = """📖 Kendi kendine ödeme yapamazsın."""
inlineReceiveFailedMessage = """🚫 İstek başarısız."""
inlineReceiveCancelledMessage = """🚫 İstek iptal edildi."""