Compare commits

..
211 Commits
Author SHA1 Message Date
gohumble d7de4bc901 massive update 2 2022-09-05 22:40:39 +02:00
gohumble d90d37e8f9 massive update 2022-09-01 10:04:48 +02:00
gohumble e385cb7bcf Merge branch 'main' into log
# Conflicts:
#	go.mod
#	internal/api/lightning.go
#	internal/api/middleware.go
#	internal/api/server.go
#	internal/lndhub/lndhub.go
2022-08-31 22:23:52 +02:00
gohumbleandGitHub ced9446287 update error handling and logs (#411) 2022-08-31 21:02:35 +02:00
gohumbleandGitHub 94ed7d4692 dalle admin api. Added configurable worker (#410) 2022-08-31 20:09:55 +02:00
gohumbleandGitHub d3c2fe7117 disable dalle if key is empty (#409) 2022-08-31 19:32:24 +02:00
calleandGitHub 5c950ef1be Merge pull request #408 from LightningTipBot/webapp_remove_href
remove href
2022-08-31 16:54:59 +02:00
callebtc 51ac159072 remove href 2022-08-31 16:54:19 +02:00
gohumbleandGitHub 857649150d fix format (#407) 2022-08-31 16:07:04 +02:00
calleandGitHub 842a037029 Merge pull request #404 from LightningTipBot/mutex_states
jobchan
2022-08-31 15:54:05 +02:00
gohumble 5aa76f86da Merge remote-tracking branch 'origin/mutex_states' into mutex_states
# Conflicts:
#	internal/telegram/generate.go
2022-08-31 15:47:56 +02:00
gohumble e170394eb8 add workerId 2022-08-31 15:44:29 +02:00
calleandGitHub 65842b056d Merge pull request #406 from LightningTipBot/buttons/help
readd help button
2022-08-31 15:36:21 +02:00
callebtc 979d3c58a2 readd help button 2022-08-31 15:35:47 +02:00
callebtc b4cb695e33 merge with main 2022-08-31 11:02:09 +02:00
callebtc 89552a73b7 changes from main 2022-08-31 10:58:50 +02:00
calleandGitHub d5f18a0d3a Merge pull request #405 from LightningTipBot/dalle_errormsgs
error feedback
2022-08-30 23:38:44 +02:00
callebtc e24490b05c error feedback 2022-08-30 23:38:17 +02:00
gohumble f288bb05f6 added jobchan and 2 workers 2022-08-30 23:23:40 +02:00
gohumble 3055f6d317 mutex state 2022-08-30 23:00:07 +02:00
calleandGitHub f19a6dd6cc Merge pull request #403 from LightningTipBot/dalle_refund_username
username for refund
2022-08-30 21:50:48 +02:00
callebtc cd55ee075b username for refund 2022-08-30 21:50:29 +02:00
calleandGitHub 9d3f856d02 Merge pull request #402 from LightningTipBot/dalle_require_private_chat
require private chat interceptor
2022-08-30 21:30:19 +02:00
gohumble f2b59140fa add deadlines 2022-08-30 21:26:42 +02:00
calleandGitHub c21d42d1e8 Merge pull request #401 from LightningTipBot/dalle_timeout_increase
Dalle timeout increase
2022-08-30 19:55:32 +02:00
callebtc 2dd2dde231 times 2022-08-30 19:53:19 +02:00
callebtc 5e3432fe32 timeout 5m 2022-08-30 19:52:36 +02:00
calleandGitHub c6df59e51b Merge pull request #400 from LightningTipBot/dalle_retry1
Dalle retry1
2022-08-30 19:46:56 +02:00
gohumble b4081df2fa Merge remote-tracking branch 'origin/dalle_retry1' into dalle_retry1 2022-08-30 19:46:21 +02:00
gohumble 9b9ceb8793 add deadlines 2022-08-30 19:46:04 +02:00
callebtc 3069126971 werks 2022-08-30 19:35:05 +02:00
callebtc b56f5e73b0 refund message 2022-08-30 19:12:47 +02:00
callebtc 42efc918c1 mutex 2022-08-30 19:07:24 +02:00
callebtc 8c75f2f947 refund 2022-08-30 19:05:38 +02:00
callebtc 7d9c0d0c8a retry 2022-08-30 18:56:05 +02:00
calleandGitHub b77f92c9b2 Merge pull request #399 from LightningTipBot/dalle2_deactivate
deactivate
2022-08-30 18:37:14 +02:00
callebtc ec2de611e4 deactivate 2022-08-30 18:36:42 +02:00
calleandGitHub 1b69313fc5 Merge pull request #398 from LightningTipBot/dalle_fix/fix1
prompt check
2022-08-30 18:18:13 +02:00
callebtc 55fc5eaa54 prompt check 2022-08-30 18:17:47 +02:00
calleandGitHub 6bc6ef215a Merge pull request #397 from LightningTipBot/dalle
Dalle
2022-08-30 18:06:42 +02:00
callebtc 52ac3bfc13 fix kraut 2022-08-30 18:06:16 +02:00
callebtc fea7281e29 lesgo 2022-08-30 18:05:01 +02:00
gohumble d992d5858f error handling 2022-08-30 17:51:43 +02:00
gohumble 2569f0d12e error handling 2022-08-30 17:50:48 +02:00
gohumble 6bdd24e4a3 downloadAndSendImages + log 2022-08-30 17:48:56 +02:00
callebtc 3c862d59ff docu 2022-08-30 17:43:30 +02:00
callebtc 2c4d499cd9 add dalle data folder 2022-08-30 17:40:13 +02:00
callebtc 2e4a793c20 dalle config 2022-08-30 17:32:45 +02:00
callebtc 890448ce81 ux 2022-08-30 17:16:38 +02:00
callebtc 08d6a0e369 Merge branch 'main' into dalle 2022-08-30 16:28:17 +02:00
gohumble 069029fbb3 fixes 2022-08-30 16:25:59 +02:00
gohumble 92f9ba1550 added dalle 2022-08-30 16:15:14 +02:00
gohumble 98bc70fc7c update invoice + mock 2022-08-30 15:20:41 +02:00
gohumble 1ee38a2989 initial dalle 2022-08-30 15:01:32 +02:00
calleandGitHub 3353bedc7a Merge pull request #396 from LightningTipBot/lnurlauth/button_text
adjust button text
2022-08-30 10:40:39 +02:00
callebtc 30c1e3231d oof 2022-08-30 10:40:10 +02:00
callebtc a3ed8ab931 adjust button text 2022-08-30 10:39:29 +02:00
calleandGitHub 3772f056a8 Merge pull request #394 from LightningTipBot/webapp/bootstrap6
href on qrcore
2022-08-29 02:42:53 +02:00
callebtc 65d933a6d5 href on qrcore 2022-08-29 02:42:30 +02:00
calleandGitHub 4038a03184 Merge pull request #393 from LightningTipBot/webapp/bootstrap5
fix currency index
2022-08-29 02:34:24 +02:00
callebtc 2c8a653c3a fix currency index 2022-08-29 02:34:09 +02:00
calleandGitHub 03509adcd1 Merge pull request #392 from LightningTipBot/webapp/bootstrap4
fiat floats
2022-08-29 02:25:59 +02:00
callebtc 74655219f3 fiat floats 2022-08-29 02:25:42 +02:00
calleandGitHub 74c057ce8e Merge pull request #391 from LightningTipBot/webapp/bootstrap3
fiat currencies
2022-08-29 02:22:46 +02:00
callebtc 0aeec7e488 fiat currencies 2022-08-29 02:22:25 +02:00
calleandGitHub 921395d283 Merge pull request #390 from LightningTipBot/webapp/bootstrap2
css tweaks
2022-08-29 01:51:23 +02:00
callebtc 9b2c23cab5 css tweaks 2022-08-29 01:51:07 +02:00
calleandGitHub 3c45a80627 Merge pull request #389 from LightningTipBot/webapp/bootstrap
add bootstrap
2022-08-29 01:41:30 +02:00
callebtc 62c2cbab5f add bootstrap 2022-08-29 01:41:07 +02:00
calleandGitHub ab82b49ff5 Merge pull request #388 from LightningTipBot/lnurl/fix_amount
fix amount parser
2022-08-29 00:47:43 +02:00
callebtc 025261d595 fix amount parser 2022-08-29 00:47:11 +02:00
calleandGitHub ed6ea4d33c Merge pull request #387 from LightningTipBot/lnurlp/fiat_price
allow fiat amount in lnurlp server
2022-08-28 22:36:58 +02:00
callebtc 69559f8aff allow fiat amount in lnurlp server 2022-08-28 22:36:04 +02:00
gohumble 2535fd3248 minor fixes 2022-08-28 22:02:21 +02:00
calleandGitHub 00406553e4 Merge pull request #386 from LightningTipBot/webview/number_input
number keyboard
2022-08-28 21:50:41 +02:00
callebtc c237e55a29 number keyboard 2022-08-28 21:50:20 +02:00
calleandGitHub 24b2c2413c Merge pull request #385 from LightningTipBot/webapp/scroll_up
scroll up
2022-08-28 21:32:02 +02:00
callebtc cb19e7375a scroll up 2022-08-28 21:31:35 +02:00
calleandGitHub 55ba146592 Merge pull request #384 from LightningTipBot/webapp/test2
Webapp/test2
2022-08-28 20:43:45 +02:00
callebtc 52230d486e clean 2022-08-28 20:43:18 +02:00
callebtc c8e45de27d invoices 2022-08-28 20:37:45 +02:00
gohumble d2922e7cc8 added FileOutput hook 2022-08-28 20:34:55 +02:00
callebtc 6a01936c2e Merge branch 'main' into webapp/test2 2022-08-28 19:28:52 +02:00
calleandGitHub 48374ad2a1 Merge pull request #383 from LightningTipBot/buttons/readd_send
readd send
2022-08-28 19:27:15 +02:00
callebtc 5b5f0ef6a2 readd send 2022-08-28 19:26:49 +02:00
callebtc b618b1aa41 create invoices 2022-08-28 19:16:23 +02:00
calleandGitHub c5f106187f Merge pull request #382 from LightningTipBot/webapp/test1
Webapp/test1
2022-08-28 15:20:42 +02:00
callebtc f35473b010 webapp log 2022-08-28 15:19:40 +02:00
callebtc 359ae13057 remove bs 2022-08-28 15:08:49 +02:00
callebtc 8d0bf2cce7 padding 2022-08-28 15:06:22 +02:00
callebtc f5c3d9fb55 webapp works 2022-08-28 14:59:30 +02:00
calleandGitHub 56c391b24e Merge pull request #381 from LightningTipBot/intercept/callbacks
callback responses
2022-08-27 16:40:56 +02:00
callebtc cbdc8638bd callback responses 2022-08-27 16:39:35 +02:00
calleandGitHub 046baab3e1 Merge pull request #380 from LightningTipBot/paybutton/unique
pay button with unique_id
2022-08-27 15:23:42 +02:00
callebtc f0f3a7c5d0 pay button with unique_id 2022-08-27 15:23:08 +02:00
calleandGitHub 43eb4966bc Merge pull request #379 from LightningTipBot/callebtc-patch-1
Update README.md
2022-08-22 09:43:38 +02:00
calleandGitHub 0d112e19de Update README.md 2022-08-22 09:43:30 +02:00
calleandGitHub 649be03c29 Merge pull request #378 from LightningTipBot/api_auth_refactor
auth refactor
2022-08-22 09:35:54 +02:00
callebtc 5e4c045312 log 2022-08-22 09:35:43 +02:00
callebtc 44f397e2de fix lndhub 2022-08-22 09:32:30 +02:00
callebtc 9451032552 user decoder 2022-08-22 09:13:39 +02:00
callebtc 8180d3cfae auth refactor 2022-08-22 09:09:53 +02:00
calleandGitHub f11ac3d807 Merge pull request #377 from LightningTipBot/sse123
sse
2022-08-21 12:53:33 +02:00
callebtc cb02fd557f sse 2022-08-21 12:52:54 +02:00
calleandGitHub ac3ac51d7b Merge pull request #376 from LightningTipBot/sse123
Sse123
2022-08-21 00:49:50 +02:00
callebtc ac9cc644eb config 2022-08-21 00:48:23 +02:00
gohumble 545898dbbe revert 2022-08-21 00:29:51 +02:00
gohumble d98aa26db9 fix 2022-08-21 00:29:06 +02:00
gohumble 13c0f3b70a increase timeouts 2022-08-21 00:07:31 +02:00
gohumble 3a4f99314d sse 2022-08-21 00:02:48 +02:00
gohumble a0f7cf09e6 sse 2022-08-20 23:22:04 +02:00
gohumble bbfa7598a0 more logs 2022-08-20 22:38:36 +02:00
callebtc 0ff0d889ff sse 2022-08-20 22:33:05 +02:00
gohumble 1303429ca5 more logs 2022-08-20 21:53:32 +02:00
gohumble e82196b6fa more logs 2022-08-20 19:56:43 +02:00
gohumble 4f205abbb9 more logs 2022-08-20 19:18:18 +02:00
gohumble 5433bcee27 more logs 2022-08-20 19:18:05 +02:00
gohumble 587da5d117 more logs 2022-08-20 19:16:15 +02:00
gohumble e731cff689 more logs 2022-08-20 19:08:12 +02:00
gohumble 92d687637c more logs 2022-08-20 19:02:06 +02:00
gohumble 33674de1b6 more logs 2022-08-20 18:29:45 +02:00
gohumble 56f9e7e40b log initital commit 2022-08-20 16:22:26 +02:00
calleandGitHub 7009d3dedc Merge pull request #374 from LightningTipBot/api
Api
2022-08-20 01:05:24 +02:00
callebtc a87eac37b8 remove 2022-08-20 01:04:31 +02:00
callebtc 250c036c47 returns 2022-08-20 01:03:22 +02:00
callebtc df303ae186 invoice 2022-08-20 00:32:20 +02:00
callebtc d0d844fd4f balance check 2022-08-20 00:21:52 +02:00
gohumble dbe94b9494 fix 2022-08-20 00:19:12 +02:00
gohumble d9f373cebb Merge remote-tracking branch 'origin/api' into api
# Conflicts:
#	internal/api/lightning.go
2022-08-20 00:18:54 +02:00
gohumble d066fa9e27 set bot in api service 2022-08-20 00:17:58 +02:00
callebtc 127f95b8de boom 2022-08-20 00:17:19 +02:00
gohumble 98401546fa add user auth 2022-08-19 23:59:23 +02:00
gohumble fbc47c0fb9 fix payments 2022-08-19 23:37:28 +02:00
callebtc 0c29fec19f lnbits stuff 2022-08-19 23:36:11 +02:00
gohumble 4bcbd2fefe add auth middleware 2022-08-19 23:35:27 +02:00
gohumble a669ea86ac add api service 2022-08-19 22:55:27 +02:00
gohumble b396219792 add api service 2022-08-19 22:32:08 +02:00
calleandGitHub 4871b42f22 Merge pull request #373 from LightningTipBot/group/ticketing_name_escape
markdown escape usernames
2022-08-19 22:08:16 +02:00
callebtc 6ff264ab18 markdown escape usernames 2022-08-19 22:07:58 +02:00
calleandGitHub fff933e413 Merge pull request #372 from LightningTipBot/update_lnurl
update go-lnurl
2022-08-17 22:01:31 +02:00
callebtc 36d94ecff8 nitpick 2022-08-17 22:01:10 +02:00
gohumble aaba02020b fix fix 2022-08-17 18:06:16 +02:00
gohumble 02bbc8e5a3 fix typo 2022-08-17 17:49:30 +02:00
gohumble 61fb20e132 update go-lnurl 2022-08-17 17:44:19 +02:00
calleandGitHub 7707fbf4a5 Merge pull request #371 from LightningTipBot:lnurl/fix
again
2022-08-15 00:32:57 +02:00
callebtc dfcf576dce again 2022-08-15 00:32:34 +02:00
calleandGitHub 796abe7f96 Merge pull request #370 from LightningTipBot/lnurlp/turn_off_desc_hash_check
turn off description_hash check
2022-08-15 00:31:19 +02:00
callebtc 52e1fc043a turn off description_hash check 2022-08-15 00:30:27 +02:00
calleandGitHub 3f64ceb6c1 Merge pull request #368 from LightningTipBot/socks5
add socks5. unify client
2022-08-14 23:20:28 +02:00
gohumble 30e0ba9cdf fix example 2022-08-14 23:05:17 +02:00
gohumble f474988606 fix cfg 2022-08-14 22:44:04 +02:00
gohumble 865592b0a6 added ClientType 2022-08-14 22:04:04 +02:00
calleandGitHub 41a4946071 Merge pull request #369 from LightningTipBot:lnurlp/check_description_hash
LNULRp: check for descr hash
2022-08-14 21:53:08 +02:00
callebtc d7dc6f71aa check for descr hash 2022-08-14 21:50:14 +02:00
gohumble d9f2f87739 add socks5. unify client 2022-08-14 21:42:03 +02:00
calleandGitHub 29f03807f2 Merge pull request #366 from LightningTipBot/lnbits/errors
unpickle lnbits errors correctly
2022-08-13 12:20:36 +02:00
callebtc 042ccaf8ef unpickle lnbits errors correctly 2022-08-13 12:18:33 +02:00
calleandGitHub 4ecc65fb27 Merge pull request #365 from LightningTipBot/fix/wallet_check
check wallet nil before balance check
2022-07-26 15:12:25 +02:00
callebtc f73e027e9c check wallet nil before balance check 2022-07-26 15:12:01 +02:00
calleandGitHub b4e8721e3e Merge pull request #364 from LightningTipBot/link/silent_edit
hide link silently
2022-07-17 20:32:59 +02:00
callebtc dd87d4f6f8 hide link silently 2022-07-17 20:32:35 +02:00
calleandGitHub 8033d05f7e Merge pull request #363 from LightningTipBot/update/zeus_help
Update/zeus help
2022-07-17 20:18:20 +02:00
callebtc c27de372a5 update zeus help 2022-07-17 20:15:58 +02:00
callebtc bc849c5b03 Merge branch 'main' of github.com:LightningTipBot/LightningTipBot 2022-06-14 16:06:27 +02:00
calleandGitHub 6f2a95609e Tip error (#362)
* tip no error message
2022-06-14 16:06:16 +02:00
callebtc d6e9f49cd1 Merge branch 'main' of github.com:LightningTipBot/LightningTipBot 2022-06-01 19:17:53 +02:00
d2a63c07a3 Transactions int64 amount (#356)
* webln and image

* transactions with int64 amounts

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-05-31 10:49:42 +02:00
callebtc 8729011aaf Merge branch 'main' of github.com:LightningTipBot/LightningTipBot 2022-05-29 16:18:00 +02:00
calleandGitHub 5199e4c8c6 Anon lnurl help message (#354)
* webln and image

* anon lnurl output
2022-05-29 16:17:23 +02:00
callebtc e5928defd0 Merge branch 'main' of github.com:LightningTipBot/LightningTipBot 2022-05-29 16:11:17 +02:00
calleandGitHub 1167392140 Stadress: better help (#353)
* webln and image

* Satdress: better logging and help
2022-05-09 13:44:37 +02:00
callebtc cf68245012 Merge branch 'main' of github.com:LightningTipBot/LightningTipBot 2022-05-09 13:34:32 +02:00
calleandGitHub 6c06a4972e Satdress lnd tor (#352)
* webln and image

* Satdress: LND over tor
2022-05-07 21:31:47 +02:00
callebtc e7fa555506 Merge branch 'main' of github.com:LightningTipBot/LightningTipBot 2022-05-07 21:30:25 +02:00
calleandGitHub 666eecf207 Userpages: site name (#351)
* webln and image

* site_name
2022-05-03 18:04:56 +02:00
callebtc 0eaf96749f Merge branch 'main' of github.com:LightningTipBot/LightningTipBot 2022-05-03 18:03:26 +02:00
calleandGitHub 672402616e webln and image (#350) 2022-05-03 17:32:35 +02:00
callebtc cfde78e639 webln and image 2022-05-03 17:31:31 +02:00
calleandGitHub fce4fb9ecc satdress timeout (#349) 2022-05-02 23:50:23 +02:00
1946a0e873 Satdress: Socks Proxy (2) (#348)
* 🚧 using socks

* socks proxy

* refactor http client

* remove comments

* remove comments

Co-authored-by: gohumble <lngohumble@gmail.com>
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-05-02 23:36:51 +02:00
LightningTipBotandGitHub fd531e6719 Revert "Satdress: Socks proxy (#346)" (#347)
This reverts commit 94ff302d15.
2022-05-02 23:28:51 +02:00
94ff302d15 Satdress: Socks proxy (#346)
* 🚧 using socks

* socks proxy

* refactor http client

* remove comments

* remove comments

Co-authored-by: gohumble <lngohumble@gmail.com>
2022-05-02 23:25:41 +02:00
LightningTipBotandGitHub 631c314b31 Revert "random_colors (#344)" (#345)
This reverts commit 307967b61a.
2022-04-30 13:46:57 +02:00
307967b61a random_colors (#344)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 13:35:03 +02:00
a53f8e307a Userpage: ln.tips link (#343)
* small note

* rem instead of px

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 13:08:42 +02:00
6f14fab93b send card template (#342)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 12:04:42 +02:00
99a866854b send_to_card (#341)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 12:02:33 +02:00
21f5abbb25 Userpage metadata (#340)
* new pic

* round logo

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 11:22:43 +02:00
158990f46d userpage log (#339)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 10:44:06 +02:00
c00196e9d6 design (#338)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-30 02:30:22 +02:00
410f56aaf5 Userpage (#337)
* userpage init

* page

* files

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-29 22:05:28 +02:00
0631fd53eb WIP: Satdress (#331)
* satdress rebase

* check config

* satdress rebase

* check config

* check for invoices

* return error

* Update inline photo v5 (#332)

* update url

* round logo

* resize

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

* new logo (#333)

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

* help (#334)

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

* add file (#335)

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

* markdown (#336)

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

* satdress rebase

* check config

* satdress rebase

* check for invoices

* return error

* satdress works

* add lnbits

* timeout

* error checking

* small lnd

* errors

* button fix

Co-authored-by: LightningTipBot <88730856+LightningTipBot@users.noreply.github.com>
2022-04-29 14:28:12 +02:00
afcd530d06 markdown (#336)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-16 00:39:12 +02:00
5aaf9452b5 add file (#335)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-16 00:35:17 +02:00
b07053172b help (#334)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-16 00:20:52 +02:00
6ebb5688fd new logo (#333)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-14 19:49:49 +02:00
2e3a1fe087 Update inline photo v5 (#332)
* update url

* round logo

* resize

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-04-14 15:35:34 +02:00
calleandGitHub 997faa2c45 increase timeout (#330) 2022-04-11 15:09:14 +02:00
calleandGitHub 048141908e Group help text (#329)
* group help text

* string

* add group to help
2022-04-09 21:20:20 +02:00
900ce09aa6 notify group (#328)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-03-31 23:29:58 +02:00
calleandGitHub bd41dd078b remove telebot on error log (#327) 2022-03-27 23:14:13 +02:00
bf643f103d 🪄 update telebot v3 🤖 (#325)
* 🚧 minor changes to all handlers...

* 🚧 passing callback to tryEditStack

* 🚧 edit and delete callback messages

* 🚧 refactor again

* 🚧 uncomment this

* 🚧 using ctx.Message().Text

* 🚧 refactor

* 🚧 refactor

* 🚧 uncomment

* context not queruy

* 🚧 update forked lightningtipbot

* 🚧 reset ArticleResult

* fix inline receive

* readd shop

* remove chat from shopView

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-03-27 22:19:38 +02:00
bassimandGitHub 23db317c0d Update en.toml (#326)
fixed typos in photoQrNotRecognizedMessage
2022-03-27 11:26:40 +02:00
calleandGitHub 7085b4dbf6 base_fee (#323) 2022-03-17 10:22:47 +01:00
calleandGitHub 9895498237 lower fee (#322) 2022-03-17 09:36:47 +01:00
calleandGitHub 4a93019428 ticket type fix (#321) 2022-03-17 00:29:06 +01:00
71d8aa202c Group invite link management (#310)
* group invite link

* link

* works

* ticketinvoiceevent type

* Add invoice event interface

* add AssertEventType

* generalize AssertEventType invocation

* wip: payment button

* all new

* callback

* fix TicketEvent Key()

* invoiceEvent in ticketEvent

* fix errors

* add payment button

* commission

* minimum price

* remove redundant ticket event data

* commission

* fixes

* update balance

* notify user if ticket < 10

* commission rounding error

* refactor

* refactor

* /join

* add /join handler

* fix handler

* fix /join

* fix handler

* fix /join interceptor

* add startUserInterceptor

* delete qr

* no test blyad

* fix defer

* message

Co-authored-by: gohumble <lngohumble@gmail.com>
2022-03-17 00:21:28 +01:00
gohumbleandGitHub a9f6539eaf 🪄 fix LNURL states redundant initialization (#318) 2022-02-27 15:33:04 +03:00
gohumbleandGitHub 1179800a4b 🪄 fix withdraw state handler (#316) 2022-02-26 10:53:15 +03:00
calleandGitHub a5d8c5d7e5 lnurl amounts same (#315) 2022-02-25 14:11:05 +03:00
0dcf4bd845 fix the tipjar and send a summary (#312)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-17 17:14:25 +01:00
92 changed files with 7443 additions and 1694 deletions
+3 -3
View File
@@ -1,5 +1,5 @@
<p align="center">
<img alt="logo" src="resources/logo_round.png" >
<img alt="logo" width="150" src="resources/logo_round.png" >
</p>
# @LightningTipBot 🏅
@@ -58,7 +58,7 @@ You can either use your own LNbits instance (recommended) or create an account a
- `lnbits_webhook_server`: URL that lnbits can reach the bot with. This is used for creating webhooks from LNbits to receive notifications about payments (optional).
- `message_dispose_duration`: Duration in seconds after which `/tip` are deleted from a channel (only if the bot is channel admin).
- `http_proxy` uses a proxy for all LNURL-related outbound requests (optional).
- `lnurl_public_host_name` is the public URL of your lnbits/LndHub (for BlueWallet/Zap support, optional).
- `lnurl_public_host_name` is the public URL of your lnbits/LndHub (for BlueWallet/Zeus support, optional).
- `lnurl_server` is the public URL for inbound LNURL payments and your lightning address host (optional).
## Features
@@ -116,7 +116,7 @@ Users can send and receive via . For this to work, you need to set the `lnurl_pu
Every user has a [Lightning Address](https://lightningaddress.com/) a la `username@host.com` with which they can send to via `/send <amount> <user@domain.com>` and receive from other wallets.
### Link to BlueWallet or Zap
### Link to BlueWallet or Zeus
Every user can link their wallet to an external app like [Bluewallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/) by using the command `/link`. If you host the bot, you will have to enable the LndHub extension in LNbits. You also need to edit the `lnbits_public_url` entry in `config.yaml` accordingly to an address that can be reached by the user's wallet (Tor should be fine as well).
+1 -1
View File
@@ -7,11 +7,11 @@
help - Read the help.
balance - Check balance.
transactions - List transactions
tip - Reply to a message to tip: /tip 50
send - Send funds to a user: /send 100 @LightningTipBot
invoice - Receive with Lightning: /invoice 1000
pay - Pay with Lightning: /pay lnbc10n1ps...
donate - Donate: /donate 1000
faucet - Create a faucet: /faucet 2100 21
tipjar - Create a tipjar: /tipjar 100 10
advanced - Advanced help
+12
View File
@@ -1,8 +1,15 @@
bot:
socks_proxy:
host: 127.0.0.1:9996
username: test
password: username
tor_proxy:
host: 127.0.0.1:9050
http_proxy: ""
lnurl_public_host_name: "mylnurl.com"
lnurl_server: "https://mylnurl.com"
lnurl_image: true
admin_api_host: localhost:6060
telegram:
message_dispose_duration: 10
api_key: "1234"
@@ -17,3 +24,8 @@ database:
buntdb_path: "data/bunt.db"
transactions_path: "data/transactions.db"
shop_buntdb_path: "data/shop.db"
groupsdb_path: "data/groups.db"
generate:
dalle_key: "asd"
dalle_price: 1000
worker: 2
+1
View File
@@ -0,0 +1 @@
this is where dalle images are stored
+81 -11
View File
@@ -1,31 +1,101 @@
module github.com/LightningTipBot/LightningTipBot
go 1.15
go 1.17
require (
github.com/BurntSushi/toml v0.3.1
github.com/btcsuite/btcd v0.20.1-beta.0.20200515232429-9f0179fd2c46 // indirect
github.com/PuerkitoBio/goquery v1.8.0
github.com/btcsuite/btcd/btcec/v2 v2.2.0
github.com/eko/gocache v1.2.0
github.com/fiatjaf/go-lnurl v1.8.4
github.com/fiatjaf/go-lnurl v1.11.2
github.com/fiatjaf/ln-decodepay v1.1.0
github.com/gorilla/mux v1.8.0
github.com/imroc/req v0.3.0
github.com/jinzhu/configor v1.2.1
github.com/makiuchi-d/gozxing v0.0.2
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
github.com/nicksnyder/go-i18n/v2 v2.1.2
github.com/orcaman/concurrent-map v1.0.0
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/sethvargo/go-limiter v0.7.2
github.com/sirupsen/logrus v1.6.0
github.com/r3labs/sse v0.0.0-20210224172625-26fe804710bc
github.com/sirupsen/logrus v1.8.1
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
github.com/tidwall/buntdb v1.2.7
github.com/tidwall/gjson v1.10.2
golang.org/x/text v0.3.5
golang.org/x/time v0.0.0-20191024005414-555d28b269f0
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211217193303-c005cce171ac
github.com/tidwall/gjson v1.12.1
github.com/tidwall/sjson v1.2.4
go.elastic.co/ecslogrus v1.0.0
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f
golang.org/x/text v0.3.7
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220828121412-0dea11ecc6dd
gopkg.in/natefinch/lumberjack.v2 v2.0.0
gorm.io/driver/sqlite v1.1.4
gorm.io/gorm v1.21.12
)
// replace gopkg.in/lightningtipbot/telebot.v2 => ../telebot
require (
github.com/XiaoMi/pegasus-go-client v0.0.0-20210427083443-f3b6b08bc4c2 // indirect
github.com/aead/siphash v1.0.1 // indirect
github.com/andybalholm/cascadia v1.3.1 // indirect
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b // indirect
github.com/btcsuite/btcd v0.23.1 // indirect
github.com/btcsuite/btcd/btcutil v1.1.1 // indirect
github.com/btcsuite/btcd/btcutil/psbt v1.1.4 // indirect
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 // indirect
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f // indirect
github.com/btcsuite/btcwallet v0.15.1 // indirect
github.com/btcsuite/btcwallet/wallet/txauthor v1.2.3 // indirect
github.com/btcsuite/btcwallet/wallet/txrules v1.2.0 // indirect
github.com/btcsuite/btcwallet/wallet/txsizes v1.1.0 // indirect
github.com/btcsuite/btcwallet/walletdb v1.4.0 // indirect
github.com/btcsuite/btcwallet/wtxmgr v1.5.0 // indirect
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd // indirect
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792 // indirect
github.com/cenkalti/backoff/v4 v4.1.0 // indirect
github.com/cespare/xxhash/v2 v2.1.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/decred/dcrd/crypto/blake256 v1.0.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
github.com/decred/dcrd/lru v1.0.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/go-errors/errors v1.0.1 // indirect
github.com/go-redis/redis/v8 v8.8.2 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.2 // indirect
github.com/kkdai/bstream v1.0.0 // indirect
github.com/lightninglabs/gozmq v0.0.0-20191113021534-d20a764486bf // indirect
github.com/lightninglabs/neutrino v0.14.2 // indirect
github.com/lightningnetwork/lnd v0.15.0-beta // indirect
github.com/lightningnetwork/lnd/clock v1.1.0 // indirect
github.com/lightningnetwork/lnd/queue v1.1.0 // indirect
github.com/lightningnetwork/lnd/ticker v1.1.0 // indirect
github.com/lightningnetwork/lnd/tlv v1.0.3 // indirect
github.com/lightningnetwork/lnd/tor v1.0.1 // indirect
github.com/magefile/mage v1.9.0 // indirect
github.com/mattn/go-sqlite3 v1.14.5 // indirect
github.com/miekg/dns v1.1.43 // indirect
github.com/nbd-wtf/ln-decodepay v1.5.1 // indirect
github.com/pegasus-kv/thrift v0.13.0 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/tidwall/btree v0.6.1 // indirect
github.com/tidwall/grect v0.1.3 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/tidwall/rtred v0.1.2 // indirect
github.com/tidwall/tinyqueue v0.1.1 // indirect
go.opentelemetry.io/otel v0.20.0 // indirect
go.opentelemetry.io/otel/metric v0.20.0 // indirect
go.opentelemetry.io/otel/trace v0.20.0 // indirect
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect
golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde // indirect
golang.org/x/sys v0.0.0-20220817070843-5a390386f1f2 // indirect
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
k8s.io/apimachinery v0.0.0-20191123233150-4c4803ed55e3 // indirect
)
// replace gopkg.in/lightningtipbot/telebot.v3 => ../telebot
+771 -89
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -68,7 +68,7 @@ func (s Service) getUserByTelegramId(r *http.Request) (*lnbits.User, error) {
if v["id"] == "" {
return nil, fmt.Errorf("invalid id")
}
tx := s.bot.Database.Where("telegram_id = ? COLLATE NOCASE", v["id"]).First(user)
tx := s.bot.DB.Users.Where("telegram_id = ? COLLATE NOCASE", v["id"]).First(user)
if tx.Error != nil {
return nil, tx.Error
}
+14
View File
@@ -0,0 +1,14 @@
package admin
import (
"github.com/LightningTipBot/LightningTipBot/internal/dalle"
"net/http"
)
func (s Service) DisableDalle(w http.ResponseWriter, r *http.Request) {
dalle.Enabled = false
}
func (s Service) EnableDalle(w http.ResponseWriter, r *http.Request) {
dalle.Enabled = true
}
+27
View File
@@ -0,0 +1,27 @@
package api
type BalanceResponse struct {
Balance int64 `json:"balance"`
}
type InvoiceStatusResponse struct {
State string `json:"state,omitempty"`
PaymentHash string `json:"payment_hash"`
Preimage int64 `json:"preimage"`
}
type CreateInvoiceResponse struct {
PaymentHash string `json:"payment_hash"`
PayRequest string `json:"pay_request"`
Preimage string `json:"preimage,omitempty"`
}
type CreateInvoiceRequest struct {
Memo string `json:"memo"`
Amount int64 `json:"amount"`
DescriptionHash string `json:"description_hash"`
UnhashedDescription string `json:"unhashed_description"`
}
type PayInvoiceRequest struct {
PayRequest string `json:"pay_req"`
}
+204
View File
@@ -0,0 +1,204 @@
package api
import (
"encoding/json"
log "github.com/sirupsen/logrus"
"net/http"
"time"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/gorilla/mux"
"github.com/r3labs/sse"
)
type Service struct {
Bot *telegram.TipBot
}
type ErrorResponse struct {
Message string `json:"error"`
}
func RespondError(w http.ResponseWriter, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
log.WithFields(log.Fields{"module": "api", "func": "RespondError"}).Error(message)
json.NewEncoder(w).Encode(ErrorResponse{Message: message})
}
func (s Service) Balance(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
balance, err := s.Bot.GetUserBalance(user)
if err != nil {
RespondError(w, "balance check failed")
return
}
balanceResponse := BalanceResponse{
Balance: balance,
}
log.WithFields(log.Fields{
"module": "api",
"func": "PayInvoice",
"user": user.GetUserStr(),
"user_id": user.ID,
"amount": balance,
"wallet_id": user.Wallet.ID,
"telegram_id": user.Telegram.ID}).Info("checked balance")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(balanceResponse)
}
func (s Service) CreateInvoice(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
var createInvoiceRequest CreateInvoiceRequest
err := json.NewDecoder(r.Body).Decode(&createInvoiceRequest)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Amount: createInvoiceRequest.Amount,
Out: false,
DescriptionHash: createInvoiceRequest.DescriptionHash,
UnhashedDescription: createInvoiceRequest.UnhashedDescription,
Webhook: internal.Configuration.Lnbits.WebhookServer},
s.Bot.Client)
if err != nil {
RespondError(w, "could not create invoice")
return
}
log.WithFields(log.Fields{
"module": "api",
"func": "CreateInvoice",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"amount": createInvoiceRequest.Amount,
"invoice": invoice.PaymentRequest,
"telegram_id": user.Telegram.ID}).Info("created invoice")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(invoice)
}
func (s Service) PayInvoice(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
var payInvoiceRequest PayInvoiceRequest
err := json.NewDecoder(r.Body).Decode(&payInvoiceRequest)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: payInvoiceRequest.PayRequest}, s.Bot.Client)
if err != nil {
RespondError(w, "could not pay invoice: "+err.Error())
return
}
payment, _ := s.Bot.Client.Payment(*user.Wallet, invoice.PaymentHash)
if err != nil {
// we assume that it's paid since thre was no error earlier
payment.Paid = true
}
log.WithFields(log.Fields{
"module": "api",
"func": "PayInvoice",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"invoice": invoice.PaymentRequest,
"telegram_id": user.Telegram.ID}).Info("payed invoice")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(payment)
}
func (s Service) PaymentStatus(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
payment_hash := mux.Vars(r)["payment_hash"]
payment, err := s.Bot.Client.Payment(*user.Wallet, payment_hash)
if err != nil {
RespondError(w, "could not get payment")
return
}
log.WithFields(log.Fields{
"module": "api",
"func": "PayInvoice",
"user": user.GetUserStr(),
"user_id": user.ID,
"status": payment.Paid,
"wallet_id": user.Wallet.ID,
"telegram_id": user.Telegram.ID}).Info("returning payment status")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(payment)
}
// InvoiceStatus
func (s Service) InvoiceStatus(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
payment_hash := mux.Vars(r)["payment_hash"]
user.Wallet = &lnbits.Wallet{}
payment, err := s.Bot.Client.Payment(*user.Wallet, payment_hash)
if err != nil {
RespondError(w, "could not get invoice")
return
}
log.WithFields(log.Fields{
"module": "api",
"func": "PayInvoice",
"user": user.GetUserStr(),
"user_id": user.ID,
"status": payment.Paid,
"wallet_id": user.Wallet.ID,
"telegram_id": user.Telegram.ID}).Info("returning invoice status")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(payment)
}
type InvoiceStream struct {
CheckingID string `json:"checking_id"`
Pending bool `json:"pending"`
Amount int `json:"amount"`
Fee int `json:"fee"`
Memo string `json:"memo"`
Time int `json:"time"`
Bolt11 string `json:"bolt11"`
Preimage string `json:"preimage"`
PaymentHash string `json:"payment_hash"`
Extra struct {
} `json:"extra"`
WalletID string `json:"wallet_id"`
Webhook string `json:"webhook"`
WebhookStatus interface{} `json:"webhook_status"`
}
func (s Service) InvoiceStream(w http.ResponseWriter, r *http.Request) {
user := telegram.LoadUser(r.Context())
w.Header().Set("Content-Type", "application/stream+json")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
flusher, err := w.(http.Flusher)
if !err {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}
client := sse.NewClient(fmt.Sprintf("%s/api/v1/payments/sse", internal.Configuration.Lnbits.Url))
client.Headers = map[string]string{"X-Api-Key": user.Wallet.Inkey}
client.Subscribe("", func(msg *sse.Event) {
if msg.Data != nil {
fmt.Fprintf(w, "%s\n", string(msg.Data))
flusher.Flush()
}
})
time.Sleep(time.Second * 5)
}
+104 -4
View File
@@ -1,21 +1,121 @@
package api
import (
"context"
"encoding/base64"
"fmt"
"net/http"
"net/http/httputil"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"gorm.io/gorm"
log "github.com/sirupsen/logrus"
)
func LoggingMiddleware(prefix string, next http.HandlerFunc) http.HandlerFunc {
func LoggingMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Tracef("[%s] %s %s", prefix, r.Method, r.URL.Path)
log.Tracef("[%s]\n%s", prefix, dump(r))
r.BasicAuth()
log.WithFields(log.Fields{"module": "api", "method": r.Method, "path": r.URL.Path, "request": dump(r)}).Info("incoming api request")
next.ServeHTTP(w, r)
}
}
type AuthType struct {
Type string
Decoder func(s string) ([]byte, error)
}
var AuthTypeBasic = AuthType{Type: "Basic"}
var AuthTypeBearerBase64 = AuthType{Type: "Bearer", Decoder: base64.StdEncoding.DecodeString}
var AuthTypeNone = AuthType{}
// invoice key or admin key requirement
type AccessKeyType struct {
Type string
}
var AccessKeyTypeInvoice = AccessKeyType{Type: "invoice"}
var AccessKeyTypeAdmin = AccessKeyType{Type: "admin"}
var AccessKeyTypeNone = AccessKeyType{Type: "none"} // no authorization required
func AuthorizationMiddleware(database *gorm.DB, authType AuthType, accessType AccessKeyType, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if accessType.Type == "none" {
next.ServeHTTP(w, r)
return
}
auth := r.Header.Get("Authorization")
// check if the user is banned
if auth == "" {
w.WriteHeader(401)
log.WithFields(log.Fields{"module": "api", "func": "AuthorizationMiddleware"}).Warn("no auth")
return
}
_, password, ok := parseAuth(authType, auth)
if !ok {
w.WriteHeader(401)
return
}
// first we make sure that the password is not already "banned_"
if strings.Contains(password, "_") || strings.HasPrefix(password, "banned_") {
w.WriteHeader(401)
log.WithFields(log.Fields{"module": "api", "func": "AuthorizationMiddleware", "user": password}).Warn("Banned user. Not forwarding request")
return
}
// then we check whether the "normal" password provided is in the database (it should be not if the user is banned)
user := &lnbits.User{}
var tx *gorm.DB
if accessType.Type == "admin" {
tx = database.Where("wallet_adminkey = ? COLLATE NOCASE", password).First(user)
} else if accessType.Type == "invoice" {
tx = database.Where("wallet_inkey = ? COLLATE NOCASE", password).First(user)
} else {
log.WithFields(log.Fields{"module": "api", "func": "AuthorizationMiddleware", "user": password, "error": tx.Error}).
Warnf("route without access type")
w.WriteHeader(401)
return
}
if tx.Error != nil {
log.WithFields(log.Fields{"module": "api", "func": "AuthorizationMiddleware", "user": password, "error": tx.Error}).
Warnf("could not load access key")
w.WriteHeader(401)
return
}
log.WithFields(log.Fields{"module": "api", "func": "AuthorizationMiddleware", "path": fmt.Sprintf("%s %s%s", r.Method, r.URL.Path, r.URL.RawQuery), "user": user.GetUserStr()}).
Debugf("Loaded Api user")
r = r.WithContext(context.WithValue(r.Context(), "user", user))
next.ServeHTTP(w, r)
}
}
// parseAuth parses an HTTP Basic Authentication string.
// "Bearer QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
func parseAuth(authType AuthType, auth string) (username, password string, ok bool) {
parse := func(prefix string) (username, password string, ok bool) {
// Case insensitive prefix match. See Issue 22736.
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
return
}
if authType.Decoder != nil {
c, err := authType.Decoder(auth[len(prefix):])
if err != nil {
return
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return
}
return cs[:s], cs[s+1:], true
}
return auth[len(prefix):], auth[len(prefix):], true
}
return parse(fmt.Sprintf("%s ", authType.Type))
}
func dump(r *http.Request) string {
x, err := httputil.DumpRequest(r, true)
if err != nil {
+3 -2
View File
@@ -2,16 +2,17 @@ package api
import (
"fmt"
log "github.com/sirupsen/logrus"
"io"
"net/http"
"net/url"
"time"
log "github.com/sirupsen/logrus"
)
func Proxy(wr http.ResponseWriter, req *http.Request, rawUrl string) error {
client := &http.Client{Timeout: time.Second * 10}
client := &http.Client{Timeout: time.Second * 30}
//http: Request.RequestURI can't be set in client requests.
//http://golang.org/src/pkg/net/http/client.go
+16 -6
View File
@@ -5,7 +5,8 @@ import (
"net/http"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"gorm.io/gorm"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
@@ -24,8 +25,8 @@ func NewServer(address string) *Server {
srv := &http.Server{
Addr: address,
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 90 * time.Second,
ReadTimeout: 90 * time.Second,
}
apiServer := &Server{
httpServer: srv,
@@ -33,7 +34,7 @@ func NewServer(address string) *Server {
apiServer.router = mux.NewRouter()
apiServer.httpServer.Handler = apiServer.router
go apiServer.httpServer.ListenAndServe()
log.Infof("[LNURL] Server started at %s", internal.Configuration.Bot.LNURLServerUrl.Host)
log.WithFields(log.Fields{"module": "api"}).Infof("Server started at %s", address)
return apiServer
}
@@ -43,15 +44,24 @@ func (w *Server) ListenAndServe() {
func (w *Server) PathPrefix(path string, handler http.Handler) {
w.router.PathPrefix(path).Handler(handler)
}
func (w *Server) AppendAuthorizedRoute(path string, authType AuthType, accessType AccessKeyType, database *gorm.DB, handler func(http.ResponseWriter, *http.Request), methods ...string) {
r := w.router.HandleFunc(path, LoggingMiddleware(AuthorizationMiddleware(database, authType, accessType, handler)))
if len(methods) > 0 {
r.Methods(methods...)
}
}
func (w *Server) AppendRoute(path string, handler func(http.ResponseWriter, *http.Request), methods ...string) {
r := w.router.HandleFunc(path, LoggingMiddleware("API", handler))
r := w.router.HandleFunc(path, LoggingMiddleware(handler))
if len(methods) > 0 {
r.Methods(methods...)
}
}
func NotFoundHandler(writer http.ResponseWriter, err error) {
log.Errorln(err)
log.WithFields(log.Fields{
"module": "api",
"func": "NotFoundHandler",
"error": err.Error()}).Errorln("Returning Http 404")
// return 404 on any error
http.Error(writer, "404 page not found", http.StatusNotFound)
}
@@ -0,0 +1,79 @@
<!-- @format -->
{{define "userpage"}}
<!DOCTYPE html>
<meta charset="utf-8" />
<meta property="og:title" content="Pay to {{.Username}}@ln.tips">
<meta property="og:site_name" content="{{.Username}}@ln.tips">
<meta property="og:description" content="Send bitcoin to {{.Username}} over Lightning. Get your own Lightning address at https://ln.tips 👈">
<meta property="og:type" content="article" />
<meta property="og:image" content="{{.Image}}">
<meta property="og:url" content="https://ln.tips/@{{.Username}}">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image:alt" content="Pay to {{.Username}}@ln.tips">
<meta name="lightning" content="lnurlp:{{.Username}}@ln.tips"/>
<title>{{.Username}}@ln.tips</title>
<script src="https://unpkg.com/kjua@0.6.0/dist/kjua.min.js"></script>
<style>
body {
background: rgb(36,71,247);
background: radial-gradient(circle, rgba(36,71,247,1) 0%, rgba(249,42,84,1) 100%);
margin: auto;
text-align: center;
font-family: monospace;
width: 600px;
color: #f3f3f3c5 !important;
}
.image-cropper {
width: 100px;
height: 100px;
position: relative;
overflow: hidden;
border-radius: 50%;
}
#photo {
margin-top: 50px;
width: 100px;
}
.white {
color: #f3f3f3c5;
}
.sm {
color: #f3f3f3c5;
font-size: 1rem;
}
#qr {
display: block;
margin-top: 50px;
margin-bottom: 50px;
}
#invoice {
margin: 10px;
padding-bottom: 10px;
white-space: pre-wrap;
word-wrap: break-word;
word-break: break-all;
font-size: 1.5rem;
}
</style>
<a href="https://t.me/{{.Username}}"><img id="photo" class="image-cropper" src="{{.Image}}"/></a>
<h1>Pay to <a class="white" href="https://t.me/{{.Username}}">{{.Username}}@ln.tips</a></h1>
<div><a href="lightning:{{.LNURLPay}}" id="qr"></a></div>
<div class="white" id="invoice">{{.LNURLPay}}</div>
<div class="sm">Get your own Lightning address here: <a class="sm" href="https://ln.tips">ln.tips</a></div>
<script>
qr.appendChild(
kjua({
text: invoice.innerHTML,
rounded: 50,
size: 500,
render: 'canvas',
})
)
</script>
{{end}}
+387
View File
@@ -0,0 +1,387 @@
<!-- @format -->
{{define "webapp"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="format-detection" content="telephone=no" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="MobileOptimized" content="176" />
<meta name="HandheldFriendly" content="True" />
<meta name="robots" content="noindex,nofollow" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title>@LightningTipBot</title>
<script src="https://unpkg.com/kjua@0.6.0/dist/kjua.min.js"></script>
<script src="https://telegram.org/js/telegram-web-app.js?1"></script>
<script>
function setThemeClass() {
document.documentElement.className = Telegram.WebApp.colorScheme;
}
Telegram.WebApp.onEvent('themeChanged', setThemeClass);
setThemeClass();
</script>
<style>
body {
font-family: sans-serif;
background-color: var(--tg-theme-bg-color, #ffffff);
color: var(--tg-theme-text-color, #222222);
font-size: 16px;
margin: 0;
padding: 0;
color-scheme: var(--tg-color-scheme);
}
a {
color: var(--tg-theme-link-color, #2678b6);
}
button {
display: block;
width: 100%;
font-size: 14px;
border: none;
background-color: var(--tg-theme-button-color, #50a8eb);
color: var(--tg-theme-button-text-color, #ffffff);
cursor: pointer;
}
.btn-primary {
background-color: var(--tg-theme-button-color, #50a8eb);
color: var(--tg-theme-button-text-color, #ffffff);
}
button[disabled] {
opacity: 0.6;
cursor: auto;
pointer-events: none;
}
input {
font-size: 14px;
text-align: center;
border: none;
background-color: var(--tg-theme-bg-color, #f5f5f5) !important;
color: var(--tg-theme-text-color, #1a1a1a) !important;
}
.input-group-text {
background-color: var(--tg-theme-bg-color, #f5f5f5) !important;
color: var(--tg-theme-text-color, #1a1a1a) !important;
}
section {
padding: 5px 5px 65px;
text-align: center;
}
p {
margin: 40px 0 15px;
}
ul {
text-align: left;
}
li {
color: var(--tg-theme-hint-color, #a8a8a8);
}
textarea {
width: 100%;
box-sizing: border-box;
padding: 7px;
}
pre {
background: rgba(0, 0, 0, .07);
border-radius: 4px;
padding: 4px;
margin: 7px 0;
word-break: break-all;
word-break: break-word;
white-space: pre-wrap;
text-align: left;
}
.dark pre {
background: rgba(255, 255, 255, .15);
}
.hint {
font-size: .8em;
color: var(--tg-theme-hint-color, #a8a8a8);
}
.ok {
color: green;
}
.err {
color: red;
}
#fixed_wrap {
position: fixed;
left: 0;
right: 0;
top: 0;
transform: translateY(100vh);
}
.viewport_border,
.viewport_stable_border {
position: fixed;
left: 0;
right: 0;
top: 0;
height: var(--tg-viewport-height, 100vh);
pointer-events: none;
}
.viewport_stable_border {
height: var(--tg-viewport-stable-height, 100vh);
}
.viewport_border:before,
.viewport_stable_border:before {
content: attr(text);
display: inline-block;
position: absolute;
background: gray;
right: 0;
top: 0;
font-size: 7px;
padding: 2px 4px;
vertical-align: top;
}
.viewport_stable_border:before {
background: green;
left: 0;
right: auto;
}
.viewport_border:after,
.viewport_stable_border:after {
content: '';
display: block;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
border: 2px dashed gray;
}
.viewport_stable_border:after {
border-color: green;
}
small {
font-size: 12px;
}
h1 {
font-size: 120%;
word-wrap: break-word;
margin: 0.5em;
}
.qr-container {
position: relative;
display: flex;
flex-direction: column;
height: 100%;
width: 100%;
}
.qr {
display: flex;
justify-content: center;
margin: 0px;
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.qr > canvas {
max-height: 800px;
max-width: 800px;
width: 100% !important;
height: 100% !important;
}
.wrapper {
display: grid;
grid-template-columns: 3fr 2fr;
padding: 12px 20px;
column-gap: 10px;
row-gap: 1em;
align-items: center;
}
</style>
</head>
<body>
<section>
<h1 id="greeting"></h1>
<div class="qr-container">
<div class="qr" id="qr">
</div>
</div>
<div id="buttons">
<!-- <button onclick="webviewClose();">Close</button> -->
<div class="wrapper">
<label class="sr-only" for="inlineFormInputGroup">Username</label>
<div class="input-group">
<input type="number" class="form-control" min="1" inputmode="numeric" pattern="[0-9]*" id="invoiceAmount" placeholder="amount">
<div class="input-group-append">
<div class="input-group-text" id="inputCurrency"></div>
</div>
</div>
<div>
<button class="btn btn-primary" onclick="invoiceButtonClick();" style="display: inline;" id="requestInvoice">Invoice</button>
</div>
</div>
</div>
</section>
<script type="application/javascript">
Telegram.WebApp.ready();
// render the LNURL pay QR code
var s = "{{.LNURLPay}}";
const currencies = ["sat", "USD", "EUR"];
var currency_idx = 0;
document.getElementById("inputCurrency").innerHTML = currencies[0];
renderQr(s);
// data passed form telegram server
const initData = Telegram.WebApp.initData || '';
const initDataUnsafe = Telegram.WebApp.initDataUnsafe || {};
document.querySelector('#greeting').innerHTML = "{{.Username}}@ln.tips";
// document.querySelector('#initData').innerHTML = JSON.stringify(initData, null, 2);
// document.querySelector('#initDataUnsafe').innerHTML = JSON.stringify(initDataUnsafe, null, 2);
// react to theme changes
try {
document.querySelector('#themeData').html(JSON.stringify(Telegram.WebApp.themeParams, null, 2));
Telegram.WebApp.onEvent('themeChanged', function() {
document.querySelector('#themeData').innerHTML = JSON.stringify(Telegram.WebApp.themeParams, null, 2);
});
} catch (error) {
console.error(error);
}
// listen for enter in input field
var el = document.getElementById("invoiceAmount");
el.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
document.getElementById("requestInvoice").click();
}
document.getElementById("requestInvoice").innerHTML = "Invoice"
// revert color of button
$('#requestInvoice').removeClass('btn-danger').addClass('btn-primary');
});
var el = document.getElementById("inputCurrency");
el.addEventListener("click", function(event) {
currency_idx += 1;
$(this).html(currencies[currency_idx%(currencies.length)]);
$('#requestInvoice').removeClass('btn-danger').addClass('btn-primary');
});
// ------------------ functions ------------------
function invoiceButtonClick() {
var c = "{{.Callback}}";
getInvoice(this, c);
// hide keyboard and scroll up
document.getElementById("invoiceAmount").blur();
window.scrollTo(0, 0);
}
function invoiceButtonDisplayError(message) {
btn = document.getElementById("requestInvoice")
btn.innerHTML = message
// update color of button
$('#requestInvoice').removeClass('btn-primary').addClass('btn-danger');
}
function webviewClose() {
Telegram.WebApp.close();
}
function renderQr(payload) {
const qr = document.getElementById('qr');
qr.innerHTML = '';
if ( qr ) {
const qrGfx = kjua({
text: payload,
rounded: 50,
size: 500,
render: 'canvas',
});
qr.appendChild( qrGfx );
// var href_link = "lightning:" + payload;
// qr.setAttribute('href', "javascript:window.open('"+ href_link+ "');" );
}
}
function getInvoice(el, callback) {
curr_idx = currency_idx%currencies.length
var invoiceAmount = Number(document.getElementById("invoiceAmount").value);
if ((currencies[curr_idx] == "sat" && !Number.isInteger(invoiceAmount)) || invoiceAmount < 1) {
invoiceButtonDisplayError("Invalid")
return false;
}
var amountQueryParam;
if (currencies[curr_idx] == "sat") {
amountQueryParam = invoiceAmount * 1000 // sat to msat
} else {
amountQueryParam = invoiceAmount + currencies[curr_idx]
}
fetch(callback)
.then(data => {
return data.json();
})
.then(r => {
console.log(r);
console.log("requesting invoice with amount " + amountQueryParam);
fetch(r.callback + '?amount='+ amountQueryParam).then(data => {
return data.json();
})
.then(r => {
console.log(r);
if (r.status == "OK"){
// update qr code
renderQr(r.pr);
document.querySelector('#greeting').innerHTML = "Pay " + invoiceAmount + " " + currencies[curr_idx];
} else {
invoiceButtonDisplayError("Error")
return false;
}
})
})
}
</script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
{{end}}
+123
View File
@@ -0,0 +1,123 @@
package userpage
import (
"embed"
"errors"
"fmt"
"html/template"
"net/http"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/PuerkitoBio/goquery"
"github.com/fiatjaf/go-lnurl"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
type Service struct {
bot *telegram.TipBot
}
func New(b *telegram.TipBot) Service {
return Service{
bot: b,
}
}
const botImage = "https://avatars.githubusercontent.com/u/88730856?v=7"
//go:embed static
var templates embed.FS
var userpage_tmpl = template.Must(template.ParseFS(templates, "static/userpage.html"))
var qr_tmpl = template.Must(template.ParseFS(templates, "static/webapp.html"))
var Client = &http.Client{
Timeout: 10 * time.Second,
}
// thank you fiatjaf for this code
func (s Service) getTelegramUserPictureURL(username string) (string, error) {
// with proxy:
// client, err := s.network.GetHttpClient()
// if err != nil {
// return "", err
// }
client := http.Client{
Timeout: 5 * time.Second,
}
resp, err := client.Get("https://t.me/" + username)
if err != nil {
return "", err
}
defer resp.Body.Close()
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return "", err
}
url, ok := doc.Find(`meta[property="og:image"]`).First().Attr("content")
if !ok {
return "", errors.New("no image available for this user")
}
return url, nil
}
func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
// https://ln.tips/@<username>
username := strings.ToLower(mux.Vars(r)["username"])
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, username)
log.WithFields(log.Fields{
"module": "api",
"func": "UserPageHandler",
"user": username}).Infof("rendering page")
lnurlEncode, err := lnurl.LNURLEncode(callback)
if err != nil {
log.WithFields(log.Fields{
"module": "api",
"func": "UserPageHandler",
"user": username,
"error": err.Error()}).Errorln("[UserPage]", "error encoding lnurl")
return
}
image, err := s.getTelegramUserPictureURL(username)
if err != nil || image == "https://telegram.org/img/t_logo.png" {
// replace the default image
image = botImage
}
if err := userpage_tmpl.ExecuteTemplate(w, "userpage", struct {
Username string
Image string
LNURLPay string
}{username, image, lnurlEncode}); err != nil {
log.WithFields(log.Fields{
"module": "api",
"func": "UserPageHandler",
"user": username,
"error": err.Error()}).Errorf("failed to render template")
}
}
func (s Service) UserWebAppHandler(w http.ResponseWriter, r *http.Request) {
// https://ln.tips/app/<username>
username := strings.ToLower(mux.Vars(r)["username"])
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, username)
log.Infof("[UserPage] rendering webapp of %s", username)
lnurlEncode, err := lnurl.LNURLEncode(callback)
if err != nil {
log.Errorln("[UserPage]", err)
return
}
if err := qr_tmpl.ExecuteTemplate(w, "webapp", struct {
Username string
LNURLPay string
Callback string
}{username, lnurlEncode, callback}); err != nil {
log.Errorf("failed to render template")
}
}
+22 -6
View File
@@ -14,15 +14,30 @@ var Configuration = struct {
Telegram TelegramConfiguration `yaml:"telegram"`
Database DatabaseConfiguration `yaml:"database"`
Lnbits LnbitsConfiguration `yaml:"lnbits"`
Generate GenerateConfiguration `yaml:"generate"`
}{}
type GenerateConfiguration struct {
DalleKey string `yaml:"dalle_key"`
DallePrice int64 `yaml:"dalle_price"`
Worker int `yaml:"worker"`
}
type SocksConfiguration struct {
Host string `yaml:"host"`
Username string `yaml:"username"`
Password string `yaml:"password"`
}
type BotConfiguration struct {
HttpProxy string `yaml:"http_proxy"`
LNURLServer string `yaml:"lnurl_server"`
LNURLServerUrl *url.URL `yaml:"-"`
LNURLHostName string `yaml:"lnurl_public_host_name"`
LNURLHostUrl *url.URL `yaml:"-"`
LNURLSendImage bool `yaml:"lnurl_image"`
SocksProxy *SocksConfiguration `yaml:"socks_proxy,omitempty"`
TorProxy *SocksConfiguration `yaml:"tor_proxy,omitempty"`
LNURLServer string `yaml:"lnurl_server"`
LNURLServerUrl *url.URL `yaml:"-"`
LNURLHostName string `yaml:"lnurl_public_host_name"`
LNURLHostUrl *url.URL `yaml:"-"`
LNURLSendImage bool `yaml:"lnurl_image"`
AdminAPIHost string `yaml:"admin_api_host"`
}
type TelegramConfiguration struct {
@@ -34,6 +49,7 @@ type DatabaseConfiguration struct {
ShopBuntDbPath string `yaml:"shop_buntdb_path"`
BuntDbPath string `yaml:"buntdb_path"`
TransactionsPath string `yaml:"transactions_path"`
GroupsDbPath string `yaml:"groupsdb_path"`
}
type LnbitsConfiguration struct {
+23
View File
@@ -0,0 +1,23 @@
package dalle
import (
"context"
"github.com/LightningTipBot/LightningTipBot/internal"
"io"
)
var Enabled bool
func init() {
if internal.Configuration.Generate.DalleKey != "" {
Enabled = true
}
}
type Client interface {
Generate(ctx context.Context, prompt string) (*Task, error)
ListTasks(ctx context.Context, req *ListTasksRequest) (*ListTasksResponse, error)
GetTask(ctx context.Context, taskID string) (*Task, error)
Download(ctx context.Context, generationID string) (io.ReadCloser, error)
Share(ctx context.Context, generationID string) (string, error)
}
+11
View File
@@ -0,0 +1,11 @@
package dalle
const (
StatusPending = "pending"
StatusRejected = "rejected"
StatusSucceeded = "succeeded"
TaskTypeText2Im = "text2im"
defaultBatchSize = 4
)
+242
View File
@@ -0,0 +1,242 @@
package dalle
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
const (
libraryVersion = "1.0.0"
defaultUserAgent = "dalle/" + libraryVersion
baseURL = "https://labs.openai.com/api/labs"
defaultHTTPClientTimeout = 15 * time.Second
)
type option func(*HTTPClient) error
func WithHTTPClient(httpClient *http.Client) option {
return func(c *HTTPClient) error {
c.httpClient = httpClient
return nil
}
}
func WithUserAgent(userAgent string) option {
return func(c *HTTPClient) error {
c.userAgent = userAgent
return nil
}
}
type HTTPClient struct {
httpClient *http.Client
userAgent string
apiKey string
}
var _ Client = (*HTTPClient)(nil)
func NewHTTPClient(apiKey string, opts ...option) (*HTTPClient, error) {
c := &HTTPClient{
httpClient: &http.Client{Timeout: defaultHTTPClientTimeout},
userAgent: defaultUserAgent,
apiKey: apiKey,
}
for _, opt := range opts {
if err := opt(c); err != nil {
return nil, err
}
}
return c, nil
}
type Task struct {
Object string `json:"object"`
ID string `json:"id"`
Created int64 `json:"created"`
TaskType string `json:"task_type"`
Status string `json:"status"`
PromptID string `json:"prompt_id"`
Prompt Prompt `json:"prompt"`
Generations Generations `json:"generations"`
}
type Generations struct {
Data []GenerationData `json:"data"`
Object string `json:"object"`
}
type GenerationData struct {
Created int64 `json:"created"`
Generation Generation `json:"generation"`
GenerationType string `json:"generation_type"`
ID string `json:"id"`
}
type Generation struct {
ImagePath string `json:"image_path"`
}
type Prompt struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
PromptType string `json:"prompt_type"`
Prompt struct {
Caption string `json:"caption"`
} `json:"prompt"`
ParentGenerationID string `json:"parent_generation_id"`
}
type GenerateRequest struct {
Prompt GenerateRequestPrompt `json:"prompt"`
TaskType string `json:"task_type"`
}
type GenerateRequestPrompt struct {
BatchSize int32 `json:"batch_size"`
Caption string `json:"caption"`
}
func (c *HTTPClient) Generate(ctx context.Context, caption string) (*Task, error) {
task := &Task{}
req := &GenerateRequest{
Prompt: GenerateRequestPrompt{
BatchSize: defaultBatchSize,
Caption: caption,
},
TaskType: TaskTypeText2Im,
}
return task, c.request(ctx, "POST", "/tasks", nil, req, task)
}
type ListTasksResponse struct {
Object string `json:"object"`
Data []Task `json:"data"`
}
type ListTasksRequest struct {
Limit int32 `json:"limit"`
}
func (c *HTTPClient) ListTasks(ctx context.Context, req *ListTasksRequest) (*ListTasksResponse, error) {
res := &ListTasksResponse{}
url := "/tasks"
if req != nil {
if req.Limit != 0 {
url += fmt.Sprintf("?limit=%d", req.Limit)
}
}
return res, c.request(ctx, "GET", url, nil, nil, res)
}
func (c *HTTPClient) GetTask(ctx context.Context, taskID string) (*Task, error) {
task := &Task{}
return task, c.request(ctx, "GET", "/tasks/"+taskID, nil, nil, task)
}
func (c *HTTPClient) Download(ctx context.Context, generationID string) (io.ReadCloser, error) {
req, err := c.createRequest(ctx, "/generations/"+generationID+"/download", "GET", nil, nil)
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("performing request: %w", err)
}
return resp.Body, nil
}
// Share makes the generation public and returns the public url
func (c *HTTPClient) Share(ctx context.Context, generationID string) (string, error) {
res := &GenerationData{}
err := c.request(ctx, "POST", "/generations/"+generationID+"/share", nil, nil, res)
if err != nil {
return "", err
}
return res.Generation.ImagePath, nil
}
func (c *HTTPClient) createRequest(ctx context.Context, path, method string, values *url.Values, data interface{}) (*http.Request, error) {
url := baseURL + path
if values != nil {
url += "?" + values.Encode()
}
var body io.Reader
if data != nil {
b, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("parsing request data: %w", err)
}
body = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, fmt.Errorf("building request: %w", err)
}
req.Header.Add("Authorization", "Bearer "+c.apiKey)
req.Header.Add("Content-Type", "application/json")
req.Header.Set("User-Agent", c.userAgent)
return req, nil
}
func (c *HTTPClient) request(ctx context.Context, method, path string, values *url.Values, body interface{}, result interface{}) error {
req, err := c.createRequest(ctx, path, method, values, body)
if err != nil {
return fmt.Errorf("creating request: %w", err)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("performing request: %w", err)
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
// TODO: improve error handling...
if resp.StatusCode != http.StatusOK {
return Error{
Message: "unexpected non 200 status code",
StatusCode: resp.StatusCode,
Details: string(respBody),
}
}
if err = json.Unmarshal(respBody, result); err != nil {
return Error{
Message: err.Error(),
StatusCode: resp.StatusCode,
Details: string(respBody),
}
}
return nil
}
type Error struct {
Message string
StatusCode int
Details string
}
func (e Error) Error() string {
return fmt.Sprintf("dalle: %s (status: %d, details: %s)", e.Message, e.StatusCode, e.Details)
}
+2 -2
View File
@@ -30,7 +30,7 @@ func MigrateAnonIdSha265Hash(db *gorm.DB) error {
_ = db.Find(&users)
for _, u := range users {
pw := u.Wallet.ID
anon_id := str.AnonIdSha256(&u)
anon_id := u.AnonIdSha256()
log.Infof("[MigrateAnonIdSha265Hash] %s -> %s", pw, anon_id)
u.AnonIDSha256 = anon_id
tx := db.Save(u)
@@ -48,7 +48,7 @@ func MigrateUUIDSha265Hash(db *gorm.DB) error {
_ = db.Find(&users)
for _, u := range users {
pw := u.Wallet.ID
uuid := str.UUIDSha256(&u)
uuid := u.UUIDSha256()
log.Infof("[MigrateUUIDSha265Hash] %s -> %s", pw, uuid)
u.UUID = uuid
tx := db.Save(u)
+53 -3
View File
@@ -1,8 +1,10 @@
package lnbits
import (
"github.com/imroc/req"
"fmt"
"time"
"github.com/imroc/req"
)
// NewClient returns a new lnbits api client. Pass your API key and url here.
@@ -83,7 +85,7 @@ func (c *Client) CreateWallet(userId, walletName, adminId string) (wal Wallet, e
}
// Invoice creates an invoice associated with this wallet.
func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx BitInvoice, err error) {
func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx Invoice, err error) {
// custom header with invoice key
invoiceHeader := req.Header{
"Content-Type": "application/json",
@@ -130,6 +132,54 @@ func (c Client) Info(w Wallet) (wtx Wallet, err error) {
return
}
// Payments returns wallet payments
func (c Client) Payments(w Wallet) (wtx Payments, err error) {
// custom header with invoice key
invoiceHeader := req.Header{
"Content-Type": "application/json",
"Accept": "application/json",
"X-Api-Key": w.Inkey,
}
resp, err := req.Get(c.url+"/api/v1/payments?limit=60", invoiceHeader, nil)
if err != nil {
return
}
if resp.Response().StatusCode >= 300 {
var reqErr Error
resp.ToJSON(&reqErr)
err = reqErr
return
}
err = resp.ToJSON(&wtx)
return
}
// Payment state of a payment
func (c Client) Payment(w Wallet, payment_hash string) (payment LNbitsPayment, err error) {
// custom header with invoice key
invoiceHeader := req.Header{
"Content-Type": "application/json",
"Accept": "application/json",
"X-Api-Key": w.Inkey,
}
resp, err := req.Get(c.url+fmt.Sprintf("/api/v1/payments/%s", payment_hash), invoiceHeader, nil)
if err != nil {
return
}
if resp.Response().StatusCode >= 300 {
var reqErr Error
resp.ToJSON(&reqErr)
err = reqErr
return
}
err = resp.ToJSON(&payment)
return
}
// Wallets returns all wallets belonging to an user
func (c Client) Wallets(w User) (wtx []Wallet, err error) {
resp, err := req.Get(c.url+"/usermanager/api/v1/wallets/"+w.ID, c.header, nil)
@@ -149,7 +199,7 @@ func (c Client) Wallets(w User) (wtx []Wallet, err error) {
}
// Pay pays a given invoice with funds from the wallet.
func (w Wallet) Pay(params PaymentParams, c *Client) (wtx BitInvoice, err error) {
func (w Wallet) Pay(params PaymentParams, c *Client) (wtx Invoice, err error) {
// custom header with admin key
adminHeader := req.Header{
"Content-Type": "application/json",
+108 -16
View File
@@ -4,12 +4,15 @@ import (
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"time"
"github.com/btcsuite/btcd/btcec"
"github.com/LightningTipBot/LightningTipBot/internal/satdress"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/imroc/req"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
type Client struct {
@@ -33,6 +36,71 @@ type User struct {
AnonIDSha256 string `json:"anon_id_sha256"`
UUID string `json:"uuid"`
Banned bool `json:"banned"`
Settings *Settings `json:"settings" gorm:"foreignKey:id"`
}
func (u User) Log() map[string]interface{} {
logMap := make(map[string]interface{})
logMap["user_id"] = u.ID
if u.Wallet != nil {
logMap["wallet_id"] = u.Wallet.ID
}
if u.Telegram != nil {
logMap["telegram_id"] = u.Telegram.ID
logMap["user_name"] = u.GetUserStr()
}
return logMap
}
func (u User) GetUserStr() string {
userStr := fmt.Sprintf("@%s", u.Telegram.Username)
// if user does not have a username
if len(userStr) < 2 && u.Telegram.FirstName != "" {
userStr = fmt.Sprintf("%s", u.Telegram.FirstName)
} else if len(userStr) < 2 {
userStr = fmt.Sprintf("%d", u.Telegram.ID)
}
return userStr
}
func (u User) GetUserStrMd() string {
userStr := fmt.Sprintf("@%s", u.Telegram.Username)
// if user does not have a username
if len(userStr) < 2 && u.Telegram.FirstName != "" {
userStr = fmt.Sprintf("[%s](tg://user?id=%d)", u.Telegram.FirstName, u.Telegram.ID)
return userStr
} else if len(userStr) < 2 {
userStr = fmt.Sprintf("[%d](tg://user?id=%d)", u.Telegram.ID, u.Telegram.ID)
return userStr
} else {
// escape only if user has a username
return str.MarkdownEscape(userStr)
}
}
func (u User) AnonIdSha256() string {
h := sha256.Sum256([]byte(u.Wallet.ID))
hash := fmt.Sprintf("%x", h)
anon_id := fmt.Sprintf("0x%s", hash[:16]) // starts with 0x because that can't be a valid telegram username
return anon_id
}
func (u User) UUIDSha256() string {
h := sha256.Sum256([]byte(u.Wallet.ID))
hash := fmt.Sprintf("%x", h)
anon_id := fmt.Sprintf("1x%s", hash[len(hash)-16:]) // starts with 1x because that can't be a valid telegram username
return anon_id
}
type Settings struct {
ID string `json:"id" gorm:"primarykey"`
Node NodeSettings `gorm:"embedded;embeddedPrefix:node_"`
}
type NodeSettings struct {
NodeType string `json:"nodetype"`
LNDParams *satdress.LNDParams `gorm:"embedded;embeddedPrefix:lndparams_"`
LNbitsParams *satdress.LNBitsParams `gorm:"embedded;embeddedPrefix:lnbitsparams_"`
}
const (
@@ -51,6 +119,7 @@ const (
UserStateShopItemSendPrice
UserStateShopItemSendItemFile
UserEnterShopsDescription
UserEnterDallePrompt
)
type UserStateKey int
@@ -61,11 +130,12 @@ func (u *User) ResetState() {
}
type InvoiceParams struct {
Out bool `json:"out"` // must be True if invoice is payed, False if invoice is received
Amount int64 `json:"amount"` // amount in MilliSatoshi
Memo string `json:"memo,omitempty"` // the invoice memo.
Webhook string `json:"webhook,omitempty"` // the webhook to fire back to when payment is received.
DescriptionHash string `json:"description_hash,omitempty"` // the invoice description hash.
Out bool `json:"out"` // must be True if invoice is payed, False if invoice is received
Amount int64 `json:"amount"` // amount in Satoshi
Memo string `json:"memo,omitempty"` // the invoice memo.
Webhook string `json:"webhook,omitempty"` // the webhook to fire back to when payment is received.
DescriptionHash string `json:"description_hash,omitempty"` // the invoice description hash.
UnhashedDescription string `json:"unhashed_description,omitempty"` // the unhashed invoice description.
}
type PaymentParams struct {
@@ -87,14 +157,11 @@ type TransferParams struct {
}
type Error struct {
Name string `json:"name"`
Message string `json:"message"`
Code int `json:"code"`
Status int `json:"status"`
Detail string `json:"detail"`
}
func (err Error) Error() string {
return err.Message
return err.Detail
}
type Wallet struct {
@@ -105,17 +172,42 @@ type Wallet struct {
Name string `json:"name"`
User string `json:"user"`
}
type BitInvoice struct {
type Payment struct {
CheckingID string `json:"checking_id"`
Pending bool `json:"pending"`
Amount int64 `json:"amount"`
Fee int64 `json:"fee"`
Memo string `json:"memo"`
Time int `json:"time"`
Bolt11 string `json:"bolt11"`
Preimage string `json:"preimage"`
PaymentHash string `json:"payment_hash"`
Extra struct{} `json:"extra"`
WalletID string `json:"wallet_id"`
Webhook interface{} `json:"webhook"`
WebhookStatus interface{} `json:"webhook_status"`
}
type LNbitsPayment struct {
Paid bool `json:"paid"`
Preimage string `json:"preimage"`
Details Payment `json:"details,omitempty"`
}
type Payments []Payment
type Invoice struct {
PaymentHash string `json:"payment_hash"`
PaymentRequest string `json:"payment_request"`
}
// from fiatjaf/lnurl-go
func (u User) LinkingKey(domain string) (*btcec.PrivateKey, *btcec.PublicKey) {
seedhash := sha256.Sum256([]byte(
seedHash := sha256.Sum256([]byte(
fmt.Sprintf("lnurlkeyseed:%s:%s",
domain, u.ID)))
return btcec.PrivKeyFromBytes(btcec.S256(), seedhash[:])
return btcec.PrivKeyFromBytes(seedHash[:])
}
func (u User) SignKeyAuth(domain string, k1hex string) (key string, sig string, err error) {
@@ -127,7 +219,7 @@ func (u User) SignKeyAuth(domain string, k1hex string) (key string, sig string,
return "", "", fmt.Errorf("invalid k1 hex '%s': %w", k1hex, err)
}
signature, err := sk.Sign(k1)
signature := ecdsa.Sign(sk, k1)
if err != nil {
return "", "", fmt.Errorf("error signing k1: %w", err)
}
+51 -13
View File
@@ -17,7 +17,7 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/gorilla/mux"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
)
@@ -32,7 +32,7 @@ type Server struct {
type Webhook struct {
CheckingID string `json:"checking_id"`
Pending bool `json:"pending"`
Pending int `json:"pending"`
Amount int64 `json:"amount"`
Fee int64 `json:"fee"`
Memo string `json:"memo"`
@@ -48,20 +48,22 @@ type Webhook struct {
func NewServer(bot *telegram.TipBot) *Server {
srv := &http.Server{
Addr: internal.Configuration.Lnbits.WebhookServerUrl.Host,
Addr: "0.0.0.0:5588",
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
apiServer := &Server{
c: bot.Client,
database: bot.Database,
database: bot.DB.Users,
bot: bot.Telegram,
httpServer: srv,
buntdb: bot.Bunt,
}
apiServer.httpServer.Handler = apiServer.newRouter()
go apiServer.httpServer.ListenAndServe()
log.Infof("[Webhook] Server started at %s", internal.Configuration.Lnbits.WebhookServerUrl)
log.WithFields(log.Fields{
"module": "lnbits",
"func": "NewServer", "host": internal.Configuration.Lnbits.WebhookServerUrl.String()}).Infof("started webhook server")
return apiServer
}
@@ -81,23 +83,37 @@ func (w *Server) newRouter() *mux.Router {
}
func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
log.Debugln("[Webhook] Received request")
log.WithFields(log.Fields{
"module": "webhook",
"func": "receive"}).Debugln("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(&webhookEvent)
if err != nil {
log.Errorf("[Webhook] Error decoding request: %s", err.Error())
log.WithFields(log.Fields{
"module": "webhook",
"func": "receive",
"error": err.Error()}).Errorf("Error decoding request")
writer.WriteHeader(400)
return
}
user, err := w.GetUserByWalletId(webhookEvent.WalletID)
if err != nil {
log.Errorf("[Webhook] Error getting user: %s", err.Error())
log.WithFields(log.Fields{
"module": "webhook",
"func": "receive",
"error": err.Error()}).Errorf("Error getting user")
writer.WriteHeader(400)
return
}
log.Infoln(fmt.Sprintf("[⚡️ WebHook] User %s (%d) received invoice of %d sat.", telegram.GetUserStr(user.Telegram), user.Telegram.ID, webhookEvent.Amount/1000))
amount := webhookEvent.Amount / 1000
log.WithFields(log.Fields{
"module": "webhook",
"func": "receive",
"user": user.GetUserStr(),
"telegram_id": user.Telegram.ID,
"amount": amount}).Infoln(fmt.Sprintf("User received invoice"))
writer.WriteHeader(200)
@@ -105,11 +121,27 @@ func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
txInvoiceEvent := &telegram.InvoiceEvent{Invoice: &telegram.Invoice{PaymentHash: webhookEvent.PaymentHash}}
err = w.buntdb.Get(txInvoiceEvent)
if err != nil {
log.Errorln(err)
log.WithFields(log.Fields{
"module": "webhook",
"func": "receive",
"user": user.GetUserStr(),
"telegram_id": user.Telegram.ID,
"error": err.Error(),
"amount": amount}).Errorln(err)
} else {
// do something with the event
if c := telegram.InvoiceCallback[txInvoiceEvent.Callback]; c != nil {
c(txInvoiceEvent)
if c := telegram.InvoiceCallback[txInvoiceEvent.Callback]; c.Function != nil {
if err := telegram.AssertEventType(txInvoiceEvent, c.Type); err != nil {
log.WithFields(log.Fields{
"module": "webhook",
"func": "receive",
"user": user.GetUserStr(),
"telegram_id": user.Telegram.ID,
"error": err.Error(),
"amount": amount}).Errorln("invalid event type")
return
}
go c.Function(txInvoiceEvent)
return
}
}
@@ -117,6 +149,12 @@ func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
// 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)
log.WithFields(log.Fields{
"module": "webhook",
"func": "receive",
"user": user.GetUserStr(),
"telegram_id": user.Telegram.ID,
"error": err.Error(),
"amount": amount}).Errorln("could not send fallback message")
}
}
+1 -48
View File
@@ -1,15 +1,11 @@
package lndhub
import (
"encoding/base64"
"net/http"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/api"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
)
@@ -18,51 +14,8 @@ type LndHub struct {
}
func New(bot *telegram.TipBot) LndHub {
return LndHub{database: bot.Database}
return LndHub{database: bot.DB.Users}
}
func (w LndHub) Handle(writer http.ResponseWriter, request *http.Request) {
auth := request.Header.Get("Authorization")
// check if the user is banned
if auth != "" {
_, password, ok := parseBearerAuth(auth)
if !ok {
return
}
// first we make sure that the password is not already "banned_"
if strings.Contains(password, "_") || strings.HasPrefix(password, "banned_") {
log.Warnf("[LNDHUB] Banned user %s. Not forwarding request", password)
return
}
// then we check whether the "normal" password provided is in the database (it should be not if the user is banned)
user := &lnbits.User{}
tx := w.database.Where("wallet_adminkey = ? COLLATE NOCASE", password).First(user)
if tx.Error != nil {
log.Warnf("[LNDHUB] Could not get wallet admin key %s: %v", password, tx.Error)
return
}
log.Debugf("[LNDHUB] User: %s", telegram.GetUserStr(user.Telegram))
}
// if not, proxy the request
api.Proxy(writer, request, internal.Configuration.Lnbits.Url)
}
// parseBearerAuth parses an HTTP Basic Authentication string.
// "Bearer QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
func parseBearerAuth(auth string) (username, password string, ok bool) {
const prefix = "Bearer "
// Case insensitive prefix match. See Issue 22736.
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
return
}
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
if err != nil {
return
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return
}
return cs[:s], cs[s+1:], true
}
+21 -13
View File
@@ -12,7 +12,7 @@ import (
"time"
"github.com/eko/gocache/store"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/api"
@@ -57,7 +57,7 @@ type Lnurl struct {
func New(bot *telegram.TipBot) Lnurl {
return Lnurl{
c: bot.Client,
database: bot.Database,
database: bot.DB.Users,
callbackHostname: internal.Configuration.Bot.LNURLHostUrl,
WebhookServer: internal.Configuration.Lnbits.WebhookServer,
buntdb: bot.Bunt,
@@ -81,11 +81,19 @@ func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Form value 'amount' is not set"))
return
}
amount, parseError := strconv.Atoi(stringAmount)
if parseError != nil {
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int %v", parseError))
return
var amount int64
if amount, err = strconv.ParseInt(stringAmount, 10, 64); err != nil {
// if the value wasn't a clean msat denomination, parse it
amount, err = telegram.GetAmount(stringAmount)
if err != nil {
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int: %v", err))
return
}
// GetAmount returns sat, we need msat
amount *= 1000
}
comment := request.FormValue("comment")
if len(comment) > CommentAllowed {
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Comment is too long"))
@@ -95,11 +103,11 @@ func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
// payer data
payerdata := request.FormValue("payerdata")
var payerData lnurl.PayerDataValues
err := json.Unmarshal([]byte(payerdata), &payerData)
err = json.Unmarshal([]byte(payerdata), &payerData)
if err != nil {
// api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err))
fmt.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err)
fmt.Errorf("[handleLnUrl] payerdata: %v", payerdata)
log.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err)
// log.Errorf("[handleLnUrl] payerdata: %v", payerdata)
}
response, err = w.serveLNURLpSecond(username, int64(amount), comment, payerData)
@@ -184,7 +192,7 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: api.StatusError,
Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", MinSendable, MinSendable)},
Reason: fmt.Sprintf("Amount out of bounds (min: %d sat, max: %d sat).", MinSendable/1000, MaxSendable/1000)},
}, fmt.Errorf("amount out of bounds")
}
// check comment length
@@ -229,7 +237,7 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
payerDataByte = []byte("")
}
descriptionHash, err := w.descriptionHash(metadata, string(payerDataByte))
descriptionHash, err := w.DescriptionHash(metadata, string(payerDataByte))
if err != nil {
return nil, err
}
@@ -281,8 +289,8 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
}
// descriptionHash is the SHA256 hash of the metadata
func (w Lnurl) descriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
// DescriptionHash is the SHA256 hash of the metadata
func (w Lnurl) DescriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
var hashString string
var hash [32]byte
if len(payerData) == 0 {
+135
View File
@@ -0,0 +1,135 @@
package log
import (
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
"go.elastic.co/ecslogrus"
"gopkg.in/natefinch/lumberjack.v2"
"io"
"time"
)
func init() {
log.SetLevel(log.DebugLevel)
customFormatter := new(log.TextFormatter)
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
customFormatter.FullTimestamp = true
log.SetFormatter(customFormatter)
rotateFileHook, err := NewRotateFileHook(RotateFileConfig{
Filename: "out.log",
MaxSize: 1, // megabytes
MaxBackups: 3,
MaxAge: 28,
Compress: true,
Level: log.DebugLevel,
Formatter: &ecslogrus.Formatter{},
})
//log.StandardLogger().ReportCaller = true
log.SetFormatter(customFormatter)
if err != nil {
panic(err)
}
log.AddHook(rotateFileHook)
}
// Logger is printing Text format of log map to stdout. Will also write to file using logrus hook
type Logger struct {
logger *log.Logger
vars map[string]interface{}
}
// Loggable structs provider their own logmap.
type Loggable interface {
Log() map[string]interface{}
}
func WithObjects(objects ...interface{}) *log.Entry {
fields := log.Fields{}
for _, object := range objects {
switch object.(type) {
case intercept.Context:
ctx := object.(intercept.Context)
if fields["path"] != "" {
switch {
case ctx.Message() != nil:
fields["path"] = "message"
case ctx.Query() != nil:
fields["path"] = "query"
case ctx.Callback() != nil:
fields["path"] = "callback"
}
}
// check for context uuid
if uuid := ctx.Value("uuid"); uuid != nil {
fields["uuid"] = uuid.(string)
}
// add chat info from context
if chat := ctx.Chat(); chat != nil {
fields["chat_id"] = ctx.Chat().ID
fields["title"] = ctx.Chat().Title
}
// add text as data if not set yet
if fields["data"] == "" {
fields["data"] = ctx.Text()
}
case Loggable:
// loggable structs provider their own logmap
for key, value := range object.(Loggable).Log() {
fields[key] = value
}
case time.Time:
t := object.(time.Time)
fields["runtime"] = time.Now().Sub(t).String()
case error:
err := object.(error)
fields["error"] = err.Error()
}
}
return log.StandardLogger().WithFields(fields)
}
// RotateFileConfig configuration for logfile rotation.
type RotateFileConfig struct {
Filename string
MaxSize int
MaxBackups int
MaxAge int
Compress bool
Level log.Level
Formatter log.Formatter
}
// RotateFileHook
type RotateFileHook struct {
Config RotateFileConfig
logWriter io.Writer
}
func NewRotateFileHook(config RotateFileConfig) (log.Hook, error) {
hook := RotateFileHook{
Config: config,
}
hook.logWriter = &lumberjack.Logger{
Filename: config.Filename,
MaxSize: config.MaxSize,
MaxBackups: config.MaxBackups,
MaxAge: config.MaxAge,
Compress: config.Compress,
}
return &hook, nil
}
func (hook *RotateFileHook) Levels() []log.Level {
return log.AllLevels[:hook.Config.Level+1]
}
func (hook *RotateFileHook) Fire(entry *log.Entry) (err error) {
b, err := hook.Config.Formatter.Format(entry)
if err != nil {
return err
}
hook.logWriter.Write(b)
return nil
}
+60
View File
@@ -0,0 +1,60 @@
package network
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
log "github.com/sirupsen/logrus"
"golang.org/x/net/proxy"
)
type ClientType string
const (
ClientTypeClearNet = "clearnet"
ClientTypeTor = "tor"
)
func GetClient(clientType ClientType) (*http.Client, error) {
client := http.Client{
Timeout: 10 * time.Second,
}
var cfg *internal.SocksConfiguration
switch clientType {
case ClientTypeClearNet:
cfg = internal.Configuration.Bot.SocksProxy
case ClientTypeTor:
cfg = internal.Configuration.Bot.TorProxy
default:
return nil, fmt.Errorf("[GetClient] invalid clientType")
}
if cfg == nil {
return &client, nil
}
proxyURL, _ := url.Parse(cfg.Host)
specialTransport := &http.Transport{}
specialTransport.Proxy = http.ProxyURL(proxyURL)
var auth *proxy.Auth
if cfg.Username != "" && cfg.Password != "" {
auth = &proxy.Auth{User: cfg.Username, Password: cfg.Password}
}
d, err := proxy.SOCKS5("tcp", cfg.Host, auth, &net.Dialer{
Timeout: 20 * time.Second,
Deadline: time.Now().Add(time.Second * 10),
KeepAlive: -1,
})
if err != nil {
log.Errorln(err)
return &client, nil
}
specialTransport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
return d.Dial(network, addr)
}
client.Transport = specialTransport
return &client, nil
}
+3 -1
View File
@@ -48,7 +48,9 @@ func NewPriceWatcher() *PriceWatcher {
pricewatcher.Exchanges["coinbase"] = pricewatcher.GetCoinbasePrice
pricewatcher.Exchanges["bitfinex"] = pricewatcher.GetBitfinexPrice
Price = make(map[string]float64, 0)
log.Infof("[PriceWatcher] Watcher started")
log.WithFields(log.Fields{
"module": "price",
"func": "PriceWatcher"}).Infof("Watcher started")
P = pricewatcher
return pricewatcher
}
+3 -2
View File
@@ -2,12 +2,13 @@ package rate
import (
"context"
log "github.com/sirupsen/logrus"
"strconv"
"sync"
log "github.com/sirupsen/logrus"
"golang.org/x/time/rate"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// Limiter
+30 -6
View File
@@ -69,7 +69,11 @@ func LockWithContext(ctx context.Context, s string) {
if nLocks == 0 {
Lock(s)
} else {
log.Tracef("[Mutex] Skip lock (nLocks: %d)", nLocks)
log.WithFields(log.Fields{
"module": "mutex",
"func": "Unlock",
"telegram_id": s,
}).Tracef("[Mutex] Skip lock (nLocks: %d)", nLocks)
}
nLocks++
mutexMap.Set(fmt.Sprintf("nLocks:%s", uid), nLocks)
@@ -98,7 +102,11 @@ func UnlockWithContext(ctx context.Context, s string) {
Unlock(s)
mutexMap.Remove(fmt.Sprintf("nLocks:%s", uid))
} else {
log.Tracef("[Mutex] Skip unlock (nLocks: %d)", nLocks)
log.WithFields(log.Fields{
"module": "mutex",
"func": "Unlock",
"telegram_id": s,
}).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))
@@ -108,7 +116,11 @@ func UnlockWithContext(ctx context.Context, s string) {
// 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)
log.WithFields(log.Fields{
"module": "mutex",
"func": "Lock",
"telegram_id": s,
}).Tracef("Locking attempt")
if m, ok := mutexMap.Get(s); ok {
m.(*sync.Mutex).Lock()
// write into mutex map
@@ -123,7 +135,11 @@ func Lock(s string) {
mutexMap.Set(s, m)
mutexMapSync.Unlock()
}
log.Tracef("[Mutex] Locked %s", s)
log.WithFields(log.Fields{
"module": "mutex",
"func": "Lock",
"telegram_id": s,
}).Tracef("Locked")
}
// Unlock unlocks a mutex in the mutexMap.
@@ -132,10 +148,18 @@ func Unlock(s string) {
if m, ok := mutexMap.Get(s); ok {
mutexMap.Remove(s)
m.(*sync.Mutex).Unlock()
log.Tracef("[Mutex] Unlocked %s", s)
log.WithFields(log.Fields{
"module": "mutex",
"func": "Unlock",
"telegram_id": s,
}).Tracef("Unlocked")
} else {
// this should never happen. Mutex should have been in the mutexMap.
log.Errorf("[Mutex] ⚠️⚠️⚠️ Unlock %s not in mutexMap. Skip.", s)
log.WithFields(log.Fields{
"module": "mutex",
"func": "Unlock",
"telegram_id": s,
}).Errorf("⚠️⚠️⚠️ Unlock not in mutexMap. Skip.")
}
mutexMapSync.Unlock()
}
+63
View File
@@ -0,0 +1,63 @@
package runtime
import (
"context"
"time"
)
// var retryMap cmap.ConcurrentMap
// func init() {
// retryMap = cmap.New()
// }
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
type FunctionRetry struct {
Ticker *time.Ticker
duration time.Duration
ctx context.Context
name string
}
type FunctionRetryOption func(*FunctionRetry)
func WithRetryDuration(d time.Duration) FunctionRetryOption {
return func(a *FunctionRetry) {
a.duration = d
}
}
func NewRetryTicker(ctx context.Context, name string, option ...FunctionRetryOption) *FunctionRetry {
t := &FunctionRetry{
name: name,
ctx: ctx,
}
for _, opt := range option {
opt(t)
}
if t.duration == 0 {
t.duration = defaultTickerCoolDown
}
t.Ticker = time.NewTicker(t.duration)
return t
}
func (t *FunctionRetry) Do(f func(), cancel_f func(), deadline_f func()) {
tickerMap.Set(t.name, t)
go func() {
for {
select {
case <-t.Ticker.C:
// ticker delivered signal. do function f
f()
case <-t.ctx.Done():
if t.ctx.Err() == context.DeadlineExceeded {
deadline_f()
}
if t.ctx.Err() == context.Canceled {
cancel_f()
}
return
}
}
}()
}
+346
View File
@@ -0,0 +1,346 @@
package satdress
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/network"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
)
// Much of this is from github.com/fiatjaf/makeinvoice
// but with added "checkInvoice" and http proxy support
type LNDParams struct {
Cert []byte `json:"cert" gorm:"-"`
CertString string `json:"certstring"`
Host string `json:"host"`
Macaroon string `json:"macaroon"`
}
func (l LNDParams) getCert() []byte { return l.Cert }
func (l LNDParams) isLocal() bool { return strings.HasPrefix(l.Host, "https://127.0.0.1") }
func (l LNDParams) isTor() bool { return strings.Index(l.Host, ".onion") != -1 }
type LNBitsParams struct {
Cert string `json:"certstring"`
Host string `json:"host"`
Key string `json:"key"`
}
func (l LNBitsParams) getCert() []byte { return []byte(l.Cert) }
func (l LNBitsParams) isTor() bool { return strings.Index(l.Host, ".onion") != -1 }
func (l LNBitsParams) isLocal() bool { return strings.HasPrefix(l.Host, "https://127.0.0.1") }
type BackendParams interface {
getCert() []byte
isTor() bool
isLocal() bool
}
type Params struct {
Backend BackendParams
Msatoshi int64
Description string
DescriptionHash []byte
Label string // only used for c-lightning
}
type CheckInvoiceParams struct {
Backend BackendParams
PR string
Hash []byte
Status string
}
func SetupHttpClient(useProxy bool, cert []byte) (*http.Client, error) {
var client *http.Client
if !useProxy {
client = &http.Client{
Timeout: 10 * time.Second,
}
} else {
var err error
client, err = network.GetClient(network.ClientTypeTor)
if err != nil {
return nil, err
}
}
// use a cert or skip TLS verification?
if len(cert) > 0 {
caCertPool := x509.NewCertPool()
ok := caCertPool.AppendCertsFromPEM(cert)
if !ok {
return client, fmt.Errorf("invalid root certificate")
}
client.Transport.(*http.Transport).TLSClientConfig = &tls.Config{RootCAs: caCertPool}
} else {
client.Transport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
}
return client, nil
}
func MakeInvoice(params Params) (CheckInvoiceParams, error) {
// defer func(prevTransport http.RoundTripper) {
// Client.Transport = prevTransport
// }(Client.Transport)
if params.Backend == nil {
return CheckInvoiceParams{}, errors.New("no backend specified")
}
var err error
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
if err != nil {
return CheckInvoiceParams{}, err
}
// description hash?
var hexh, b64h string
if params.DescriptionHash != nil {
hexh = hex.EncodeToString(params.DescriptionHash)
b64h = base64.StdEncoding.EncodeToString(params.DescriptionHash)
}
switch backend := params.Backend.(type) {
case LNDParams:
log.WithFields(log.Fields{
"module": "satdress",
"func": "MakeInvoice",
"host": backend.Host}).Debugf("LND invoice")
body, _ := sjson.Set("{}", "value_msat", params.Msatoshi)
if params.DescriptionHash == nil {
body, _ = sjson.Set(body, "memo", params.Description)
} else {
body, _ = sjson.Set(body, "description_hash", b64h)
}
req, err := http.NewRequest("POST",
backend.Host+"/v1/invoices",
bytes.NewBufferString(body),
)
if err != nil {
return CheckInvoiceParams{}, err
}
// macaroon must be hex, so if it is on base64 we adjust that
if b, err := base64.StdEncoding.DecodeString(backend.Macaroon); err == nil {
backend.Macaroon = hex.EncodeToString(b)
}
req.Header.Set("Grpc-Metadata-macaroon", backend.Macaroon)
resp, err := Client.Do(req)
if err != nil {
return CheckInvoiceParams{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(resp.Body)
text := string(body)
if len(text) > 300 {
text = text[:300]
}
return CheckInvoiceParams{}, fmt.Errorf("call to lnd failed (%d): %s", resp.StatusCode, text)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return CheckInvoiceParams{}, err
}
// bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
checkInvoiceParams := CheckInvoiceParams{
Backend: params.Backend,
PR: gjson.ParseBytes(b).Get("payment_request").String(),
Hash: []byte(gjson.ParseBytes(b).Get("r_hash").String()),
Status: "OPEN",
}
if len(checkInvoiceParams.PR) == 0 {
return CheckInvoiceParams{}, errors.New("could not create invoice")
}
return checkInvoiceParams, nil
case LNBitsParams:
log.WithFields(log.Fields{
"module": "satdress",
"func": "MakeInvoice",
"host": backend.Host}).Debug("LNBits invoice")
body, _ := sjson.Set("{}", "amount", params.Msatoshi/1000)
body, _ = sjson.Set(body, "out", false)
if params.DescriptionHash == nil {
if params.Description == "" {
body, _ = sjson.Set(body, "memo", "invoice")
} else {
body, _ = sjson.Set(body, "memo", params.Description)
}
} else {
body, _ = sjson.Set(body, "description_hash", hexh)
}
req, err := http.NewRequest("POST",
backend.Host+"/api/v1/payments",
bytes.NewBufferString(body),
)
if err != nil {
return CheckInvoiceParams{}, err
}
req.Header.Set("X-Api-Key", backend.Key)
req.Header.Set("Content-Type", "application/json")
resp, err := Client.Do(req)
if err != nil {
return CheckInvoiceParams{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(resp.Body)
text := string(body)
if len(text) > 300 {
text = text[:300]
}
return CheckInvoiceParams{}, fmt.Errorf("call to lnbits failed (%d): %s", resp.StatusCode, text)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return CheckInvoiceParams{}, err
}
checkInvoiceParams := CheckInvoiceParams{
Backend: params.Backend,
PR: gjson.ParseBytes(b).Get("payment_request").String(),
Hash: []byte(gjson.ParseBytes(b).Get("payment_hash").String()),
Status: "OPEN",
}
if len(checkInvoiceParams.PR) == 0 {
return CheckInvoiceParams{}, errors.New("could not create invoice")
}
return checkInvoiceParams, nil
default:
return CheckInvoiceParams{}, errors.New("wrong backend type")
}
}
func CheckInvoice(params CheckInvoiceParams) (CheckInvoiceParams, error) {
// defer func(prevTransport http.RoundTripper) {
// Client.Transport = prevTransport
// }(Client.Transport)
if params.Backend == nil {
return CheckInvoiceParams{}, errors.New("no backend specified")
}
var err error
Client, err := SetupHttpClient(!params.Backend.isLocal(), params.Backend.getCert())
if err != nil {
return CheckInvoiceParams{}, err
}
switch backend := params.Backend.(type) {
case LNDParams:
log.WithFields(log.Fields{
"module": "satdress",
"func": "CheckInvoice",
"invoice": base64.StdEncoding.EncodeToString(params.Hash),
"host": backend.Host}).Debugf("[CheckInvoice] LND invoice")
p, err := base64.StdEncoding.DecodeString(string(params.Hash))
if err != nil {
return CheckInvoiceParams{}, fmt.Errorf("invalid hash")
}
hexHash := hex.EncodeToString(p)
requestUrl, err := url.Parse(fmt.Sprintf("%s/v1/invoice/%s?r_hash=%s", backend.Host, hexHash, base64.StdEncoding.EncodeToString(params.Hash)))
if err != nil {
return CheckInvoiceParams{}, err
}
requestUrl.Scheme = "https"
req, err := http.NewRequest("GET",
requestUrl.String(), nil)
if err != nil {
return CheckInvoiceParams{}, err
}
// macaroon must be hex, so if it is on base64 we adjust that
if b, err := base64.StdEncoding.DecodeString(backend.Macaroon); err == nil {
backend.Macaroon = hex.EncodeToString(b)
}
req.Header.Set("Grpc-Metadata-macaroon", backend.Macaroon)
resp, err := Client.Do(req)
if err != nil {
return CheckInvoiceParams{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(resp.Body)
text := string(body)
if len(text) > 300 {
text = text[:300]
}
return CheckInvoiceParams{}, fmt.Errorf("call to lnd failed (%d): %s", resp.StatusCode, text)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return CheckInvoiceParams{}, err
}
params.Status = gjson.ParseBytes(b).Get("state").String()
return params, nil
case LNBitsParams:
log.WithFields(log.Fields{
"module": "satdress",
"func": "CheckInvoice",
"invoice": base64.StdEncoding.EncodeToString(params.Hash),
"host": backend.Host}).Debugf("LNBits invoice")
log.WithFields(log.Fields{
"module": "satdress",
"func": "CheckInvoice",
"invoice": base64.StdEncoding.EncodeToString(params.Hash),
"host": backend.Host + "/api/v1/payments/" + string(params.Hash)}).Debug("Fetching GET")
req, err := http.NewRequest("GET", backend.Host+"/api/v1/payments/"+string(params.Hash), nil)
if err != nil {
return CheckInvoiceParams{}, err
}
req.Header.Set("X-Api-Key", backend.Key)
req.Header.Set("Content-Type", "application/json")
resp, err := Client.Do(req)
if err != nil {
return CheckInvoiceParams{}, err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(resp.Body)
text := string(body)
if len(text) > 300 {
text = text[:300]
}
return CheckInvoiceParams{}, fmt.Errorf("call to lnbits failed (%d): %s", resp.StatusCode, text)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return CheckInvoiceParams{}, err
}
status := strings.ToLower(gjson.ParseBytes(b).Get("paid").String())
if status == "true" {
params.Status = "SETTLED"
} else {
params.Status = "OPEN"
}
return params, nil
default:
return CheckInvoiceParams{}, errors.New("missing backend params")
}
}
-17
View File
@@ -1,12 +1,9 @@
package str
import (
"crypto/sha256"
"fmt"
"hash/fnv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
)
var markdownV2Escapes = []string{"_", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!"}
@@ -41,17 +38,3 @@ func Int64Hash(s string) uint64 {
h.Write([]byte(s))
return h.Sum64()
}
func AnonIdSha256(u *lnbits.User) string {
h := sha256.Sum256([]byte(u.Wallet.ID))
hash := fmt.Sprintf("%x", h)
anon_id := fmt.Sprintf("0x%s", hash[:16]) // starts with 0x because that can't be a valid telegram username
return anon_id
}
func UUIDSha256(u *lnbits.User) string {
h := sha256.Sum256([]byte(u.Wallet.ID))
hash := fmt.Sprintf("%x", h)
anon_id := fmt.Sprintf("1x%s", hash[len(hash)-16:]) // starts with 1x because that can't be a valid telegram username
return anon_id
}
+36 -28
View File
@@ -4,9 +4,12 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/log"
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
@@ -15,8 +18,8 @@ import (
"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"
"github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
func getArgumentFromCommand(input string, which int) (output string, err error) {
@@ -29,15 +32,15 @@ func getArgumentFromCommand(input string, which int) (output string, err error)
func decodeAmountFromCommand(input string) (amount int64, err error) {
if len(strings.Split(input, " ")) < 2 {
errmsg := "message doesn't contain any amount"
// log.Errorln(errmsg)
return 0, fmt.Errorf(errmsg)
return 0, fmt.Errorf("message doesn't contain any amount")
}
amount, err = getAmount(strings.Split(input, " ")[1])
amount, err = GetAmount(strings.Split(input, " ")[1])
return amount, err
}
func getAmount(input string) (amount int64, err error) {
// GetAmount parses an amount from a string like 1.2k or 3.50€
// and returns the value in satoshis
func GetAmount(input string) (amount int64, err error) {
// convert something like 1.2k into 1200
if strings.HasSuffix(strings.ToLower(input), "k") {
fmount, err := strconv.ParseFloat(strings.TrimSpace(input[:len(input)-1]), 64)
@@ -58,7 +61,6 @@ func getAmount(input string) (amount int64, err error) {
numeric_string = strings.Replace(strings.ToLower(numeric_string), strings.ToLower(currency), "", 1) // for 1USD
fmount, err := strconv.ParseFloat(numeric_string, 64)
if err != nil {
log.Errorln(err)
return 0, err
}
if !(price.Price[currency] > 0) {
@@ -104,7 +106,9 @@ func (bot *TipBot) askForAmount(ctx context.Context, id string, eventType string
// set LNURLPayParams in the state of the user
stateDataJson, err := json.Marshal(enterAmountStateData)
if err != nil {
log.Errorln(err)
log.WithObjects(ctx, user, err).WithFields(logrus.Fields{
"module": "telegram",
"func": "askForAmount"}).Errorln("could not marshal state data")
return
}
SetUserState(user, bot, lnbits.UserEnterAmount, string(stateDataJson))
@@ -120,7 +124,7 @@ func (bot *TipBot) askForAmount(ctx context.Context, id string, eventType string
// enterAmountHandler is invoked in anyTextHandler when the user needs to enter an amount
// the amount is then stored as an entry in the user's stateKey in the user database
// any other handler that relies on this, needs to load the resulting amount from the database
func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
func (bot *TipBot) enterAmountHandler(ctx intercept.Context) (intercept.Context, error) {
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
@@ -133,25 +137,28 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) (conte
var EnterAmountStateData EnterAmountStateData
err := json.Unmarshal([]byte(user.StateData), &EnterAmountStateData)
logFields := logrus.Fields{
"module": "telegram",
"func": "enterAmountHandler",
}
if err != nil {
log.Errorf("[enterAmountHandler] %s", err.Error())
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("could not unmarshal state data")
ResetUserState(user, bot)
return ctx, err
}
amount, err := getAmount(m.Text)
amount, err := GetAmount(ctx.Message().Text)
if err != nil {
log.Warnf("[enterAmountHandler] %s", err.Error())
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
log.WithObjects(ctx, user, err).WithFields(logFields).Warnf("invalid amount")
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
ResetUserState(user, bot)
return ctx, err
}
// amount not in allowed range from LNURL
if EnterAmountStateData.AmountMin > 0 && EnterAmountStateData.AmountMax >= EnterAmountStateData.AmountMin && // this line checks whether min_max is set at all
(amount > 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))
(amount > EnterAmountStateData.AmountMax/1000 || amount < EnterAmountStateData.AmountMin/1000) { // this line then checks whether the amount is in the range
log.WithObjects(ctx, user, err).WithFields(logFields).WithFields(logrus.Fields{"data": ctx.Message().Text, "amount": amount}).Warnf("amount not in range")
bot.trySendMessage(ctx.Sender(), fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), EnterAmountStateData.AmountMin/1000, EnterAmountStateData.AmountMax/1000))
ResetUserState(user, bot)
return ctx, errors.Create(errors.InvalidSyntaxError)
}
@@ -175,17 +182,18 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) (conte
EnterAmountStateData.Amount = int64(amount) * 1000 // mSat
StateDataJson, err := json.Marshal(EnterAmountStateData)
if err != nil {
log.Errorln(err)
log.WithObjects(ctx, err, user).WithField("data", ctx.Message().Text).Errorln("error marshaling state data")
return ctx, err
}
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
return bot.lnurlPayHandlerSend(ctx, m)
return bot.lnurlPayHandlerSend(ctx)
case "LnurlWithdrawState":
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(EnterAmountStateData.ID))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.WithObjects(ctx, user, err).WithField("data", ctx.Message().Text).Warnf("transaction not found")
return ctx, err
}
LnurlWithdrawState := sn.(*LnurlWithdrawState)
@@ -196,25 +204,25 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) (conte
EnterAmountStateData.Amount = int64(amount) * 1000 // mSat
StateDataJson, err := json.Marshal(EnterAmountStateData)
if err != nil {
log.Errorln(err)
log.WithObjects(ctx, user, err).WithField("data", ctx.Message().Text).Errorln("could not marshal state data")
return ctx, err
}
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
return bot.lnurlWithdrawHandlerWithdraw(ctx, m)
return bot.lnurlWithdrawHandlerWithdraw(ctx)
case "CreateInvoiceState":
m.Text = fmt.Sprintf("/invoice %d", amount)
ctx.Message().Text = fmt.Sprintf("/invoice %d", amount)
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
return bot.invoiceHandler(ctx, m)
return bot.invoiceHandler(ctx)
case "CreateDonationState":
m.Text = fmt.Sprintf("/donate %d", amount)
ctx.Message().Text = fmt.Sprintf("/donate %d", amount)
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
return bot.donationHandler(ctx, m)
return bot.donationHandler(ctx)
case "CreateSendState":
splits := strings.SplitAfterN(EnterAmountStateData.OiringalCommand, " ", 2)
if len(splits) > 1 {
m.Text = fmt.Sprintf("/send %d %s", amount, splits[1])
ctx.Message().Text = fmt.Sprintf("/send %d %s", amount, splits[1])
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
return bot.sendHandler(ctx, m)
return bot.sendHandler(ctx)
}
return ctx, errors.Create(errors.InvalidSyntaxError)
default:
+18 -12
View File
@@ -1,21 +1,24 @@
package telegram
import (
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/log"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
logrus "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
func (bot *TipBot) balanceHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
func (bot *TipBot) balanceHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
// check and print all commands
if len(m.Text) > 0 {
bot.anyTextHandler(ctx, m)
bot.anyTextHandler(ctx)
}
logFields := ctx.Context.Value("fields").(logrus.Fields)
// reply only in private message
if m.Chat.Type != tb.ChatPrivate {
// delete message
@@ -28,18 +31,21 @@ func (bot *TipBot) balanceHandler(ctx context.Context, m *tb.Message) (context.C
}
if !user.Initialized {
return bot.startHandler(ctx, m)
return bot.startHandler(ctx)
}
usrStr := GetUserStr(m.Sender)
balance, err := bot.GetUserBalance(user)
if err != nil {
log.Errorf("[/balance] Error fetching %s's balance: %s", usrStr, err)
bot.trySendMessage(m.Sender, Translate(ctx, "balanceErrorMessage"))
log.WithObjects(user, err).WithFields(logFields).Error("Error fetching balance")
bot.trySendMessage(ctx.Sender(), Translate(ctx, "balanceErrorMessage"))
return ctx, err
}
log.Infof("[/balance] %s's balance: %d sat\n", usrStr, balance)
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "balanceMessage"), balance))
log.WithObjects(user).WithFields(logFields).WithField("amount", balance).Infof("sending balance to user")
bot.trySendMessage(ctx.Sender(), fmt.Sprintf(Translate(ctx, "balanceMessage"), balance))
return ctx, nil
}
+12 -9
View File
@@ -19,15 +19,13 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/storage"
gocache "github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
"gorm.io/gorm"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
type TipBot struct {
Database *gorm.DB
DB *Databases
Bunt *storage.DB
ShopBunt *storage.DB
logger *gorm.DB
Telegram *tb.Bot
Client *lnbits.Client
limiter map[string]limiter.Limiter
@@ -47,12 +45,11 @@ func NewBot() TipBot {
gocacheClient := gocache.New(5*time.Minute, 10*time.Minute)
gocacheStore := store.NewGoCache(gocacheClient, nil)
// create sqlite databases
db, txLogger := AutoMigration()
dbs := AutoMigration()
limiter.Start()
return TipBot{
Database: db,
DB: dbs,
Client: lnbits.NewClient(internal.Configuration.Lnbits.AdminKey, internal.Configuration.Lnbits.Url),
logger: txLogger,
Bunt: createBunt(internal.Configuration.Database.BuntDbPath),
ShopBunt: createBunt(internal.Configuration.Database.ShopBuntDbPath),
Telegram: newTelegramBot(),
@@ -66,6 +63,7 @@ func newTelegramBot() *tb.Bot {
Token: internal.Configuration.Telegram.ApiKey,
Poller: &tb.LongPoller{Timeout: 60 * time.Second},
ParseMode: tb.ModeMarkdown,
Verbose: false,
})
if err != nil {
panic(err)
@@ -79,7 +77,9 @@ func (bot TipBot) initBotWallet() error {
botWalletInitialisation.Do(func() {
_, err := bot.initWallet(bot.Telegram.Me)
if err != nil {
log.Errorln(fmt.Sprintf("[initBotWallet] Could not initialize bot wallet: %s", err.Error()))
log.WithFields(log.Fields{
"module": "telegram",
"func": "initBotWallet"}).Errorln(fmt.Sprintf("Could not initialize bot wallet: %s", err.Error()))
return
}
})
@@ -111,7 +111,10 @@ func (bot *TipBot) GracefulShutdown() {
// Start will initialize the Telegram bot and lnbits.
func (bot *TipBot) Start() {
log.Infof("[Telegram] Authorized on account @%s", bot.Telegram.Me.Username)
log.WithFields(log.Fields{
"module": "telegram",
"func": "Start",
"user": bot.Telegram.Me.Username}).Infof("Authorized on account")
// initialize the bot wallet
err := bot.initBotWallet()
if err != nil {
+48 -14
View File
@@ -3,37 +3,42 @@ package telegram
import (
"context"
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// we can't use space in the label of buttons, because string splitting will mess everything up.
const (
MainMenuCommandSend = "💸 Send"
MainMenuCommandWebApp = "⤵️ Recv"
MainMenuCommandBalance = "Balance"
MainMenuCommandInvoice = "⚡️ Invoice"
MainMenuCommandHelp = "📖 Help"
MainMenuCommandSend = "⤴️ Send"
SendMenuCommandEnter = "👤 Enter"
)
var (
mainMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
mainMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
btnHelpMainMenu = mainMenu.Text(MainMenuCommandHelp)
btnWebAppMainMenu = mainMenu.Text(MainMenuCommandWebApp)
btnSendMainMenu = mainMenu.Text(MainMenuCommandSend)
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
btnInvoiceMainMenu = mainMenu.Text(MainMenuCommandInvoice)
sendToMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
sendToMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
sendToButtons = []tb.Btn{}
btnSendMenuEnter = mainMenu.Text(SendMenuCommandEnter)
)
func init() {
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu, btnHelpMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu),
mainMenu.Row(btnBalanceMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu),
)
}
@@ -58,6 +63,21 @@ func buttonWrapper(buttons []tb.Btn, markup *tb.ReplyMarkup, length int) []tb.Ro
return rows
}
// appendWebAppLinkToButton adds a WebApp object to a Button with the user's webapp page
func (bot *TipBot) appendWebAppLinkToButton(btn *tb.Btn, user *lnbits.User) {
var url string
if len(user.Telegram.Username) > 0 {
url = fmt.Sprintf("%s/app/@%s", internal.Configuration.Bot.LNURLHostName, user.Telegram.Username)
} else {
url = fmt.Sprintf("%s/app/@%s", internal.Configuration.Bot.LNURLHostName, user.AnonIDSha256)
}
if strings.HasPrefix(url, "https://") {
// prevent adding a link if not https is used, otherwise
// Telegram returns an error and does not show the keyboard
btn.WebApp = &tb.WebAppInfo{Url: url}
}
}
// mainMenuBalanceButtonUpdate updates the balance button in the mainMenu
func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
var user *lnbits.User
@@ -72,14 +92,22 @@ func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
if user.Wallet != nil {
amount, err := bot.GetUserBalanceCached(user)
if err == nil {
log.Tracef("[appendMainMenu] user %s balance %d sat", GetUserStr(user.Telegram), amount)
log.WithFields(log.Fields{
"module": "telegram-buttons",
"func": "mainMenuBalanceButtonUpdate",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"telegram_id": user.Telegram.ID}).Tracef("user %s balance %d sat", user.GetUserStr(), amount)
MainMenuCommandBalance := fmt.Sprintf("%s %d sat", MainMenuCommandBalance, amount)
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu, btnHelpMainMenu),
)
}
bot.appendWebAppLinkToButton(&btnWebAppMainMenu, user)
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu),
)
}
}
@@ -92,13 +120,19 @@ func (bot *TipBot) makeContactsButtons(ctx context.Context) []tb.Btn {
user := LoadUser(ctx)
// get 5 most recent transactions by from_id with distint to_user
// where to_user starts with an @ and is not the user itself
bot.logger.Where("from_id = ? AND to_user LIKE ? AND to_user <> ?", user.Telegram.ID, "@%", GetUserStr(user.Telegram)).Distinct("to_user").Order("id desc").Limit(5).Find(&records)
log.Debugf("[makeContactsButtons] found %d records", len(records))
bot.DB.Transactions.Where("from_id = ? AND to_user LIKE ? AND to_user <> ?", user.Telegram.ID, "@%", user.GetUserStr()).Distinct("to_user").Order("id desc").Limit(5).Find(&records)
log.WithFields(log.Fields{
"module": "telegram-buttons",
"func": "makeContactsButtons",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"telegram_id": user.Telegram.ID}).Debugf("[makeContactsButtons] found %d records", len(records))
// get all contacts and add them to the buttons
for i, r := range records {
log.Tracef("[makeContactsButtons] toNames[%d] = %s (id=%d)", i, r.ToUser, r.ID)
sendToButtons = append(sendToButtons, tb.Btn{Text: fmt.Sprintf("%s", r.ToUser)})
sendToButtons = append(sendToButtons, tb.Btn{Text: r.ToUser})
}
// add the "enter a username" button to the end
+66 -24
View File
@@ -5,6 +5,7 @@ import (
"crypto/sha1"
"encoding/base64"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/log"
"os"
"reflect"
"runtime/debug"
@@ -20,14 +21,20 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/tidwall/buntdb"
log "github.com/sirupsen/logrus"
"github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type Databases struct {
Users *gorm.DB
Transactions *gorm.DB
Groups *gorm.DB
}
const (
MessageOrderedByReplyToFrom = "message.reply_to_message.from.id"
TipTooltipKeyPattern = "tip-tool-tip:*"
@@ -53,7 +60,7 @@ func ColumnMigrationTasks(db *gorm.DB) error {
if err != nil {
panic(err)
}
log.Info("Running anon_id database migrations ...")
logrus.Info("Running anon_id database migrations ...")
// run the migration on anon_id
err = database.MigrateAnonIdInt32Hash(db)
}
@@ -65,7 +72,7 @@ func ColumnMigrationTasks(db *gorm.DB) error {
if err != nil {
panic(err)
}
log.Info("Running anon_id_sha256 database migrations ...")
logrus.Info("Running anon_id_sha256 database migrations ...")
// run the migration on anon_id
err = database.MigrateAnonIdSha265Hash(db)
}
@@ -77,7 +84,7 @@ func ColumnMigrationTasks(db *gorm.DB) error {
if err != nil {
panic(err)
}
log.Info("Running UUID database migrations ...")
logrus.Info("Running UUID database migrations ...")
// run the migration on uuid
err = database.MigrateUUIDSha265Hash(db)
}
@@ -86,7 +93,7 @@ func ColumnMigrationTasks(db *gorm.DB) error {
return err
}
func AutoMigration() (db *gorm.DB, txLogger *gorm.DB) {
func AutoMigration() *Databases {
orm, err := gorm.Open(sqlite.Open(internal.Configuration.Database.DbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
if err != nil {
panic("Initialize orm failed.")
@@ -100,7 +107,7 @@ func AutoMigration() (db *gorm.DB, txLogger *gorm.DB) {
panic(err)
}
txLogger, err = gorm.Open(sqlite.Open(internal.Configuration.Database.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
txLogger, err := gorm.Open(sqlite.Open(internal.Configuration.Database.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
if err != nil {
panic("Initialize orm failed.")
}
@@ -108,7 +115,21 @@ func AutoMigration() (db *gorm.DB, txLogger *gorm.DB) {
if err != nil {
panic(err)
}
return orm, txLogger
groupsDb, err := gorm.Open(sqlite.Open(internal.Configuration.Database.GroupsDbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
if err != nil {
panic("Initialize orm failed.")
}
err = groupsDb.AutoMigrate(&Group{})
if err != nil {
panic(err)
}
return &Databases{
Users: orm,
Transactions: txLogger,
Groups: groupsDb,
}
}
func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.User, error) {
@@ -117,7 +138,7 @@ func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.U
if len(toUserStrWithoutAt) > 100 {
return nil, fmt.Errorf("[GetUserByTelegramUsername] Telegram username is too long: %s..", toUserStrWithoutAt[:100])
}
tx := bot.Database.Where("telegram_username = ? COLLATE NOCASE", toUserStrWithoutAt).First(toUserDb)
tx := bot.DB.Users.Where("telegram_username = ? COLLATE NOCASE", toUserStrWithoutAt).First(toUserDb)
if tx.Error != nil || toUserDb.Wallet == nil {
err := tx.Error
if toUserDb.Wallet == nil {
@@ -144,10 +165,9 @@ func getCachedUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
// without updating the user in storage.
func GetLnbitsUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
tx := bot.Database.First(user)
tx := bot.DB.Users.First(user)
if tx.Error != nil {
errmsg := fmt.Sprintf("[GetUser] Couldn't fetch %s from Database: %s", GetUserStr(u), tx.Error.Error())
log.Warnln(errmsg)
user.Telegram = u
return user, tx.Error
}
@@ -155,6 +175,23 @@ func GetLnbitsUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
return user, nil
}
func GetLnbitsUserWithSettings(u *tb.User, bot TipBot) (*lnbits.User, error) {
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
tx := bot.DB.Users.Preload("Settings").First(user)
if tx.Error != nil {
log.WithObjects(user, tx.Error).WithFields(logrus.Fields{
"module": "database",
"func": "GetLnbitsUserWithSettings",
}).Warnln(fmt.Sprintf("Couldn't preload user settings from Database"))
user.Telegram = u
return user, tx.Error
}
if user.Settings == nil {
user.Settings = &lnbits.Settings{ID: user.ID}
}
return user, nil
}
// GetUser from Telegram user. Update the user if user information changed.
func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
var user *lnbits.User
@@ -171,7 +208,10 @@ func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
user.Telegram = u
err = UpdateUserRecord(user, bot)
if err != nil {
log.Warnln(fmt.Sprintf("[UpdateUserRecord] %s", err.Error()))
log.WithObjects(user, err).WithFields(logrus.Fields{
"module": "database",
"func": "GetUser",
}).Warnln(fmt.Sprintf("UpdateUserRecord failed"))
}
}
return user, err
@@ -194,7 +234,7 @@ func debugStack() {
hasher.Write(stack)
sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
fo, err := os.Create(fmt.Sprintf("trace_%s.txt", sha))
log.Infof("[debugStack] ⚠️ Writing stack trace to %s", fmt.Sprintf("trace_%s.txt", sha))
logrus.Infof("[debugStack] ⚠️ Writing stack trace to %s", fmt.Sprintf("trace_%s.txt", sha))
if err != nil {
panic(err)
}
@@ -213,36 +253,38 @@ func debugStack() {
}
}()
}
func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
user.UpdatedAt = time.Now()
logFields := logrus.Fields{
"module": "database",
"func": "UpdateUserRecord",
}
// There is a weird bug that makes the AnonID vanish. This is a workaround.
// TODO -- Remove this after empty anon id bug is identified
if user.AnonIDSha256 == "" {
debugStack()
user.AnonIDSha256 = str.AnonIdSha256(user)
log.Errorf("[UpdateUserRecord] AnonIDSha256 empty! Setting to: %s", user.AnonIDSha256)
user.AnonIDSha256 = user.AnonIdSha256()
log.WithObjects(user).WithFields(logFields).WithField("annon_id", user.AnonIDSha256).Errorf("Setting AnonIDSha256")
}
// TODO -- Remove this after empty anon id bug is identified
if user.AnonID == "" {
debugStack()
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
log.Errorf("[UpdateUserRecord] AnonID empty! Setting to: %s", user.AnonID)
log.WithObjects(user).WithFields(logFields).WithField("annon_id", user.AnonID).Errorf("Setting AnonID")
}
// TODO -- Remove this after empty anon id bug is identified
if user.UUID == "" {
debugStack()
user.UUID = str.UUIDSha256(user)
log.Errorf("[UpdateUserRecord] UUID empty! Setting to: %s", user.UUID)
user.UUID = user.UUIDSha256()
log.WithObjects(user).WithFields(logFields).WithField("annon_id", user.UUID).Errorf("Setting UUID")
}
tx := bot.Database.Save(user)
tx := bot.DB.Users.Save(user)
if tx.Error != nil {
errmsg := fmt.Sprintf("[UpdateUserRecord] Error: Couldn't update %s's info in Database.", GetUserStr(user.Telegram))
log.Errorln(errmsg)
return tx.Error
}
log.Tracef("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
log.WithObjects(user).WithFields(logFields).Info("Updated records of user")
if bot.Cache.GoCacheStore != nil {
updateCachedUser(user, bot)
}
+25 -16
View File
@@ -3,18 +3,21 @@ package telegram
import (
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/log"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
logrus "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// PLEASE DO NOT CHANGE THE CODE IN THIS FILE
@@ -34,9 +37,13 @@ func helpDonateUsage(ctx context.Context, errormsg string) string {
}
}
func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
func (bot TipBot) donationHandler(ctx intercept.Context) (intercept.Context, error) {
// check and print all commands
bot.anyTextHandler(ctx, m)
logFields := logrus.Fields{
"module": "telegram",
"func": "donationHandler"}
m := ctx.Message()
bot.anyTextHandler(ctx)
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
@@ -52,15 +59,15 @@ func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) (context.C
// command is valid
msg := bot.trySendMessageEditable(m.Chat, Translate(ctx, "donationProgressMessage"))
// get invoice
resp, err := http.Get(fmt.Sprintf(donationEndpoint, amount, GetUserStr(user.Telegram), GetUserStr(bot.Telegram.Me)))
resp, err := http.Get(fmt.Sprintf(donationEndpoint, amount, user.GetUserStr(), GetUserStr(bot.Telegram.Me)))
if err != nil {
log.Errorln(err)
log.WithObjects(user, err, ctx).WithFields(logFields).Errorln("could not GET donation endpoint")
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorln(err)
log.WithObjects(user, err, ctx).WithFields(logFields).Errorln("could not read body")
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
@@ -70,9 +77,7 @@ func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) (context.C
// bot.trySendMessage(user.Telegram, string(body))
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: string(body)}, bot.Client)
if err != nil {
userStr := GetUserStr(user.Telegram)
errmsg := fmt.Sprintf("[/donate] Donation failed for user %s: %s", userStr, err)
log.Errorln(errmsg)
log.WithObjects(ctx, user, err).WithFields(logFields).Errorln("donation failed")
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
@@ -86,7 +91,8 @@ func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) (context.C
func init() {
var sb strings.Builder
_, err := io.Copy(&sb, rot13Reader{strings.NewReader("uggcf://ya.gvcf/qbangr/%q?sebz=%f&obg=%f")})
rot := []byte{117, 103, 103, 99, 102, 58, 47, 47, 121, 97, 46, 103, 118, 99, 102, 47, 113, 98, 97, 110, 103, 114, 47, 37, 113, 63, 115, 101, 98, 122, 61, 37, 102, 38, 111, 98, 103, 61, 37, 102}
_, err := io.Copy(&sb, rot13Reader{strings.NewReader(string(rot))})
if err != nil {
panic(err)
}
@@ -118,7 +124,10 @@ func (rot13 rot13Reader) Read(b []byte) (int, error) {
return n, err
}
func (bot TipBot) parseCmdDonHandler(ctx context.Context, m *tb.Message) error {
var d = []byte{71, 117, 110, 97, 120, 32, 108, 98, 104, 33, 32, 86, 39, 122, 32, 101, 98, 104, 103, 118, 97, 116, 32, 103, 117, 118, 102, 32, 113, 98, 97, 110, 103, 118, 98, 97, 32, 103, 98, 32, 89, 118, 116, 117, 103, 97, 118, 97, 116, 71, 118, 99, 79, 98, 103, 64, 121, 97, 46, 103, 118, 99, 102, 46}
func (bot TipBot) parseDonationCommandHandler(ctx intercept.Context) error {
m := ctx.Message()
arg := ""
if strings.HasPrefix(strings.ToLower(m.Text), "/send") {
arg, _ = getArgumentFromCommand(m.Text, 2)
@@ -142,7 +151,7 @@ func (bot TipBot) parseCmdDonHandler(ctx context.Context, m *tb.Message) error {
}
var sb strings.Builder
_, err = io.Copy(&sb, rot13Reader{strings.NewReader("Gunax lbh! V'z ebhgvat guvf qbangvba gb YvtugavatGvcObg@ya.gvcf.")})
_, err = io.Copy(&sb, rot13Reader{strings.NewReader(string(d))})
if err != nil {
panic(err)
}
@@ -150,7 +159,7 @@ func (bot TipBot) parseCmdDonHandler(ctx context.Context, m *tb.Message) error {
bot.trySendMessage(m.Sender, str.MarkdownEscape(donationInterceptMessage))
m.Text = fmt.Sprintf("/donate %d", amount)
bot.donationHandler(ctx, m)
// returning nil here will abort the parent handler (/pay or /tip)
return nil
ctx, err = bot.donationHandler(ctx)
// returning nil here will abort the parent ctx (/pay or /tip)
return err
}
+1 -1
View File
@@ -6,7 +6,7 @@ import (
cmap "github.com/orcaman/concurrent-map"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
var editStack cmap.ConcurrentMap
+109 -48
View File
@@ -7,6 +7,8 @@ import (
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/once"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
@@ -19,11 +21,11 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
var (
inlineFaucetMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
inlineFaucetMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
btnCancelInlineFaucet = inlineFaucetMenu.Data("🚫 Cancel", "cancel_faucet_inline")
btnAcceptInlineFaucet = inlineFaucetMenu.Data("✅ Collect", "confirm_faucet_inline")
)
@@ -60,7 +62,7 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
if err != nil {
return nil, errors.New(errors.DecodePerUserAmountError, err)
}
perUserAmount, err := getAmount(peruserStr)
perUserAmount, err := GetAmount(peruserStr)
if err != nil {
return nil, errors.New(errors.InvalidAmountError, err)
}
@@ -136,28 +138,27 @@ func (bot TipBot) makeFaucet(ctx context.Context, m *tb.Message, query bool) (*I
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)
func (bot TipBot) makeQueryFaucet(ctx intercept.Context) (*InlineFaucet, error) {
faucet, err := bot.createFaucet(ctx, ctx.Query().Text, ctx.Query().Sender)
if err != nil {
switch err.(errors.TipBotError).Code {
case errors.DecodeAmountError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
bot.inlineQueryReplyWithError(ctx, 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))
bot.inlineQueryReplyWithError(ctx, 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))
bot.inlineQueryReplyWithError(ctx, 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))
bot.inlineQueryReplyWithError(ctx, 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))
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.BalanceToLowError:
log.Errorf(err.Error())
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
}
}
@@ -165,7 +166,7 @@ func (bot TipBot) makeQueryFaucet(ctx context.Context, q *tb.Query, query bool)
}
func (bot TipBot) makeFaucetKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
inlineFaucetMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
inlineFaucetMenu := &tb.ReplyMarkup{ResizeKeyboard: true}
acceptInlineFaucetButton := inlineFaucetMenu.Data(Translate(ctx, "collectButtonMessage"), "confirm_faucet_inline", id)
cancelInlineFaucetButton := inlineFaucetMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_faucet_inline", id)
inlineFaucetMenu.Inline(
@@ -176,33 +177,51 @@ func (bot TipBot) makeFaucetKeyboard(ctx context.Context, id string) *tb.ReplyMa
return inlineFaucetMenu
}
func (bot TipBot) faucetHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
bot.anyTextHandler(ctx, m)
if m.Private() {
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetHelpFaucetInGroup")))
func (bot TipBot) faucetHandler(ctx intercept.Context) (intercept.Context, error) {
bot.anyTextHandler(ctx)
if ctx.Message().Private() {
bot.trySendMessage(ctx.Message().Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetHelpFaucetInGroup")))
return ctx, errors.Create(errors.NoPrivateChatError)
}
ctx = bot.mapFaucetLanguage(ctx, m.Text)
inlineFaucet, err := bot.makeFaucet(ctx, m, false)
ctx.Context = bot.mapFaucetLanguage(ctx, ctx.Text())
inlineFaucet, err := bot.makeFaucet(ctx, ctx.Message(), false)
if err != nil {
log.Warnf("[faucet] %s", err.Error())
log.WithFields(log.Fields{
"module": "telegram-faucet",
"func": "faucetHandler",
"error": err.Error()}).Warnf("could not create faucet from message")
return ctx, err
}
fromUserStr := GetUserStr(m.Sender)
mFaucet := bot.trySendMessage(m.Chat, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
log.Infof("[faucet] %s created faucet %s: %d sat (%d per user)", fromUserStr, inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
fromUserStr := GetUserStr(ctx.Message().Sender)
mFaucet := bot.trySendMessage(ctx.Message().Chat, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
log.WithFields(log.Fields{
"module": "telegram-faucet",
"func": "faucetHandler",
"user": fromUserStr,
"telegram_id": ctx.Message().Sender.ID,
"data": fmt.Sprintf("[faucet] %s created faucet %s: %d sat (%d per user)", fromUserStr, inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount),
"error": err.Error()}).Infof("created faucet")
// log faucet link if possible
if mFaucet != nil && mFaucet.Chat != nil {
log.Infof("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(mFaucet.Chat.ID, 10)[4:], mFaucet.ID)
log.WithFields(log.Fields{
"module": "telegram-faucet",
"func": "faucetHandler",
"user": fromUserStr,
"telegram_id": ctx.Message().Sender.ID,
"data": fmt.Sprintf("https://t.me/c/%s/%d", strconv.FormatInt(mFaucet.Chat.ID, 10)[4:], mFaucet.ID),
"error": err.Error()}).Infof("found faucet link")
}
return ctx, inlineFaucet.Set(inlineFaucet, bot.Bunt)
}
func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) (context.Context, error) {
inlineFaucet, err := bot.makeQueryFaucet(ctx, q, false)
func (bot TipBot) handleInlineFaucetQuery(ctx intercept.Context) (intercept.Context, error) {
inlineFaucet, err := bot.makeQueryFaucet(ctx)
if err != nil {
log.Errorf("[handleInlineFaucetQuery] %s", err.Error())
log.WithFields(log.Fields{
"module": "telegram-faucet",
"func": "handleInlineFaucetQuery",
"error": err.Error()}).Errorf("could not create faucet from query")
return ctx, err
}
urls := []string{
@@ -218,7 +237,7 @@ func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) (con
// required for photos
ThumbURL: url,
}
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeFaucetKeyboard(ctx, inlineFaucet.ID).InlineKeyboard}
result.ReplyMarkup = &tb.ReplyMarkup{InlineKeyboard: bot.makeFaucetKeyboard(ctx, inlineFaucet.ID).InlineKeyboard}
results[i] = result
// needed to set a unique string ID for each result
results[i].SetResultID(inlineFaucet.ID)
@@ -227,7 +246,7 @@ func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) (con
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{
err = bot.Telegram.Answer(ctx.Query(), &tb.QueryResponse{
Results: results,
CacheTime: 1,
})
@@ -238,14 +257,20 @@ func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) (con
return ctx, nil
}
func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
func (bot *TipBot) acceptInlineFaucetHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
to := LoadUser(ctx)
tx := &InlineFaucet{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[acceptInlineFaucetHandler] c.Data: %s, Error: %s", c.Data, err.Error())
log.WithFields(log.Fields{
"module": "telegram-faucet",
"func": "acceptInlineFaucetHandler",
"telegram_id": ctx.Message().Sender.ID,
"data": c.Data,
"error": err.Error()}).Errorf("could not fetch transaction")
return ctx, err
}
log.Tracef("[acceptInlineFaucetHandler] Callback c.Data: %s tx.ID: %s", c.Data, tx.ID)
@@ -260,21 +285,46 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
}
// log faucet link if possible
if c.Message != nil && c.Message.Chat != nil {
log.Infof("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(c.Message.Chat.ID, 10)[4:], c.Message.ID)
log.WithFields(log.Fields{
"module": "telegram-faucet",
"func": "acceptInlineFaucetHandler",
"user": GetUserStr(from.Telegram),
"user_id": from.ID,
"telegram_id": from.Telegram.ID,
"wallet_id": from.Wallet.ID,
"data": fmt.Sprintf("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(c.Message.Chat.ID, 10)[4:], c.Message.ID),
}).Infof("found faucet link")
}
// release faucet no matter what
if from.Telegram.ID == to.Telegram.ID {
log.Debugf("[faucet] %s is the owner faucet %s", GetUserStr(to.Telegram), inlineFaucet.ID)
ctx = context.WithValue(ctx, "callback_response", Translate(ctx, "sendYourselfMessage"))
log.WithFields(log.Fields{
"module": "telegram-faucet",
"func": "acceptInlineFaucetHandler",
"user": GetUserStr(from.Telegram),
"user_id": from.ID,
"telegram_id": from.Telegram.ID,
"wallet_id": from.Wallet.ID,
"data": inlineFaucet.ID,
}).Debugf("cannot drain own faucet")
ctx.Context = context.WithValue(ctx, "callback_response", Translate(ctx, "sendYourselfMessage"))
return ctx, errors.Create(errors.SelfPaymentError)
}
// check if to user has already taken from the faucet
for _, a := range inlineFaucet.To {
if a.Telegram.ID == to.Telegram.ID {
// to user is already in To slice, has taken from facuet
log.Debugf("[faucet] %s:%d already took from faucet %s", GetUserStr(to.Telegram), to.Telegram.ID, inlineFaucet.ID)
ctx = context.WithValue(ctx, "callback_response", Translate(ctx, "inlineFaucetAlreadyTookMessage"))
log.WithFields(log.Fields{
"module": "telegram-faucet",
"func": "acceptInlineFaucetHandler",
"user": GetUserStr(from.Telegram),
"to_user_id": to.ID,
"to_telegram_id": to.Telegram.ID,
"user_id": from.ID,
"telegram_id": from.Telegram.ID,
"wallet_id": from.Wallet.ID,
"data": inlineFaucet.ID,
}).Debugf("already took from faucet")
ctx.Context = context.WithValue(ctx, "callback_response", Translate(ctx, "inlineFaucetAlreadyTookMessage"))
return ctx, errors.Create(errors.UnknownError)
}
}
@@ -291,8 +341,17 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
if !exists {
to, err = bot.CreateWalletForTelegramUser(to.Telegram)
if err != nil {
errmsg := fmt.Errorf("[faucet] Error: Could not create wallet for %s", toUserStr)
log.Errorln(errmsg)
log.WithFields(log.Fields{
"module": "telegram-faucet",
"func": "acceptInlineFaucetHandler",
"to_user": GetUserStr(to.Telegram),
"to_user_id": to.ID,
"to_wallet_id": to.Wallet.ID,
"user": GetUserStr(from.Telegram),
"user_id": from.ID,
"wallet_id": from.Wallet.ID,
"error": err.Error()},
).Errorln("Could not create wallet for user")
return ctx, err
}
}
@@ -302,7 +361,7 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
}
// todo: user new get username function to get userStrings
transactionMemo := fmt.Sprintf("Faucet from %s to %s (%d sat).", fromUserStr, toUserStr, inlineFaucet.PerUserAmount)
transactionMemo := fmt.Sprintf("🚰 Faucet from %s to %s.", fromUserStr, toUserStr)
t := NewTransaction(bot, from, to, inlineFaucet.PerUserAmount, TransactionType("faucet"))
t.Memo = transactionMemo
@@ -311,7 +370,7 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
// bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
errMsg := fmt.Sprintf("[faucet] Transaction failed: %s", err.Error())
log.Warnln(errMsg)
ctx = context.WithValue(ctx, "callback_response", Translate(ctx, "errorTryLaterMessage"))
ctx.Context = context.WithValue(ctx, "callback_response", Translate(ctx, "errorTryLaterMessage"))
// if faucet fails, cancel it:
// c.Sender.ID = inlineFaucet.From.Telegram.ID // overwrite the sender of the callback to be the faucet owner
// log.Debugf("[faucet] Canceling faucet %s...", inlineFaucet.ID)
@@ -326,7 +385,7 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
inlineFaucet.RemainingAmount = inlineFaucet.RemainingAmount - inlineFaucet.PerUserAmount
go func() {
to_message := fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineFaucetReceivedMessage"), fromUserStrMd, inlineFaucet.PerUserAmount)
ctx = context.WithValue(ctx, "callback_response", to_message)
ctx.Context = context.WithValue(ctx, "callback_response", to_message)
bot.trySendMessage(to.Telegram, to_message)
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineFaucetSentMessage"), inlineFaucet.PerUserAmount, toUserStrMd))
}()
@@ -345,9 +404,8 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
// update the message if the faucet still has some sats left after this tx
if inlineFaucet.RemainingAmount >= inlineFaucet.PerUserAmount {
bot.tryEditStack(c.Message, inlineFaucet.ID, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
bot.tryEditStack(c, inlineFaucet.ID, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
}
}
if inlineFaucet.RemainingAmount < inlineFaucet.PerUserAmount {
log.Debugf(fmt.Sprintf("[faucet] faucet %s empty. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
@@ -370,7 +428,7 @@ func (bot *TipBot) cancelInlineFaucet(ctx context.Context, c *tb.Callback, ignor
inlineFaucet := fn.(*InlineFaucet)
if ignoreID || c.Sender.ID == inlineFaucet.From.Telegram.ID {
faucet_cancelled_message := i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage")
bot.tryEditStack(c.Message, inlineFaucet.ID, faucet_cancelled_message, &tb.ReplyMarkup{})
bot.tryEditStack(c, inlineFaucet.ID, faucet_cancelled_message, &tb.ReplyMarkup{})
ctx = context.WithValue(ctx, "callback_response", faucet_cancelled_message)
// set the inlineFaucet inactive
inlineFaucet.Active = false
@@ -390,7 +448,7 @@ func (bot *TipBot) finishFaucet(ctx context.Context, c *tb.Callback, inlineFauce
if inlineFaucet.UserNeedsWallet {
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
}
bot.tryEditStack(c.Message, inlineFaucet.ID, inlineFaucet.Message, &tb.ReplyMarkup{})
bot.tryEditStack(c, inlineFaucet.ID, inlineFaucet.Message, &tb.ReplyMarkup{})
log.Debugf("[faucet] Faucet finished %s", inlineFaucet.ID)
once.Remove(inlineFaucet.ID)
@@ -412,6 +470,9 @@ func listFaucetTakers(inlineFaucet *InlineFaucet) string {
return to_str
}
func (bot *TipBot) cancelInlineFaucetHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
return bot.cancelInlineFaucet(ctx, c, false)
func (bot *TipBot) cancelInlineFaucetHandler(ctx intercept.Context) (intercept.Context, error) {
var err error
ctx.Context, err = bot.cancelInlineFaucet(ctx, ctx.Callback(), false)
return ctx, err
}
+6 -5
View File
@@ -1,19 +1,20 @@
package telegram
import (
"context"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
tb "gopkg.in/lightningtipbot/telebot.v2"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
func (bot *TipBot) fileHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
func (bot *TipBot) fileHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
if m.Chat.Type != tb.ChatPrivate {
return ctx, errors.Create(errors.NoPrivateChatError)
}
user := LoadUser(ctx)
if c := stateCallbackMessage[user.StateKey]; c != nil {
// found handler for this state
// found ctx for this state
// now looking for user state reset ticker
ticker := runtime.GetTicker(user.ID)
if !ticker.Started {
@@ -27,7 +28,7 @@ func (bot *TipBot) fileHandler(ctx context.Context, m *tb.Message) (context.Cont
ticker.ResetChan <- struct{}{}
}
return c(ctx, m)
return c(ctx)
}
return ctx, errors.Create(errors.NoFileFoundError)
}
+263
View File
@@ -0,0 +1,263 @@
package telegram
import (
"bytes"
"context"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/dalle"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// generateImages is called when the user enters /generate or /generate <prompt>
// asks the user for a prompt if not given
func (bot *TipBot) generateImages(ctx intercept.Context) (intercept.Context, error) {
if !dalle.Enabled {
bot.trySendMessage(ctx.Message().Sender, "🤖💤 Dalle image generation is currently not available. Please try again later.")
return ctx, nil
}
bot.anyTextHandler(ctx)
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, fmt.Errorf("user has no wallet")
}
if len(strings.Split(ctx.Message().Text, " ")) < 2 {
// We need to save the pay state in the user state so we can load the payment in the next handler
SetUserState(user, bot, lnbits.UserEnterDallePrompt, "")
bot.trySendMessage(ctx.Message().Sender, "⌨️ Enter image prompt.", tb.ForceReply)
return ctx, nil
}
// write the prompt into the command and call confirm
m := ctx.Message()
m.Text = GetMemoFromCommand(m.Text, 1)
return bot.confirmGenerateImages(ctx)
}
// confirmGenerateImages is called when the user has entered a prompt through /generate <prompt>
// or because he answered to the request to enter it in generateImages()
// confirmGenerateImages will create an invoice that the user can pay and if they pay
// generateDalleImages will fetch the images and send it to the user
func (bot *TipBot) confirmGenerateImages(ctx intercept.Context) (intercept.Context, error) {
user := LoadUser(ctx)
ResetUserState(user, bot)
m := ctx.Message()
prompt := m.Text
if len(prompt) == 0 {
return ctx, fmt.Errorf("prompt not given")
}
if user.Wallet == nil {
return ctx, fmt.Errorf("user has no wallet")
}
me, err := GetUser(bot.Telegram.Me, *bot)
if err != nil {
return ctx, err
}
invoice, err := bot.createInvoiceWithEvent(ctx, me, internal.Configuration.Generate.DallePrice, fmt.Sprintf("DALLE2 %s", user.GetUserStr()), InvoiceCallbackGenerateDalle, prompt)
invoice.Payer = user
if err != nil {
return ctx, err
}
runtime.IgnoreError(bot.Bunt.Set(invoice))
balance, err := bot.GetUserBalance(user)
if err != nil {
errmsg := fmt.Sprintf("[inlineReceive] Error: Could not get user balance: %s", err.Error())
log.Warnln(errmsg)
}
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "generateDallePayInvoiceMessage"))
// invoke internal pay if enough balance
if balance >= internal.Configuration.Generate.DallePrice {
m.Text = fmt.Sprintf("/pay %s", invoice.PaymentRequest)
return bot.payHandler(ctx)
}
// create qr code
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
if err != nil {
bot.tryEditMessage(invoice.Message, Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
// send the invoice data to user
msg := bot.trySendMessage(ctx.Message().Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
invoice.InvoiceMessage = msg
runtime.IgnoreError(bot.Bunt.Set(invoice))
return ctx, nil
}
var jobChan chan func(workerId int)
var workers = internal.Configuration.Generate.Worker
func init() {
if workers == 0 {
log.Printf("Dalle is disabled. No worker started.")
return
}
log.Printf("Starting Dalle image generation. Worker: %d, Price: %d sat", workers, internal.Configuration.Generate.DallePrice)
jobChan = make(chan func(workerId int), workers)
for i := 0; i < workers; i++ {
go worker(jobChan, i)
}
}
func worker(linkChan chan func(workerId int), workerId int) {
for generatePrompt := range linkChan {
generatePrompt(workerId)
}
}
// generateDalleImages is called by the invoice event when the user has paid
func (bot *TipBot) generateDalleImages(event Event) {
invoiceEvent := event.(*InvoiceEvent)
user := invoiceEvent.Payer
if user == nil || user.Wallet == nil {
log.Errorf("[generateDalleImages] invalid user")
return
}
bot.trySendMessage(user.Telegram, "🔄 Your images are being generated. Please wait a few moments.")
var job = func(workerId int) {
// create the client with the bearer token api key
dalleClient, err := dalle.NewHTTPClient(internal.Configuration.Generate.DalleKey)
// handle err
if err != nil {
log.Errorf("[NewHTTPClient-%d] %v", workerId, err.Error())
bot.dalleRefundUser(user, "")
return
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*15)
defer cancel()
// generate a task to create an image with a prompt
task, err := dalleClient.Generate(ctx, invoiceEvent.CallbackData)
if err != nil {
log.Errorf("[Generate-%d] %v", workerId, err.Error())
bot.dalleRefundUser(user, "")
return
}
// poll the task.ID until status is succeeded
var t *dalle.Task
timeout := time.After(10 * time.Minute)
ticker := time.Tick(5 * time.Second)
// Keep trying until we're timed out or get a result/error
for {
select {
case <-ctx.Done():
bot.dalleRefundUser(user, "")
log.Errorf("[DALLE-%d] ctx done. Task %s", workerId, task.ID)
return
// Got a timeout! fail with a timeout error
case <-timeout:
bot.dalleRefundUser(user, "Timeout. Please try again later.")
log.Errorf("[DALLE-%d] timeout. Task: %s", workerId, task.ID)
return
// Got a tick, we should check on checkSomething()
case <-ticker:
t, err = dalleClient.GetTask(ctx, task.ID)
// handle err
if err != nil {
log.Errorf("[GetTask-%d] Task: %s. Error: %v", workerId, task.ID, err.Error())
//bot.dalleRefundUser(user, "")
continue
}
if t.Status == dalle.StatusSucceeded {
log.Printf("[DALLE-%d] task succeeded for user %s", workerId, user.GetUserStr())
// download the first generated image
for _, data := range t.Generations.Data {
err = bot.downloadAndSendImages(ctx, dalleClient, data, invoiceEvent)
if err != nil {
log.Errorf("[downloadAndSendImages-%d] Id: %s. Error: %v", workerId, data.ID, err.Error())
}
}
return
} else if t.Status == dalle.StatusRejected {
log.Errorf("[DALLE-%d] rejected: %s", workerId, t.ID)
bot.dalleRefundUser(user, "Your prompt has been rejected by OpenAI. Do not use celebrity names, sexual expressions, or any other harmful content as prompt.")
return
}
log.Debugf("[DALLE-%d] pending for user %s", workerId, user.GetUserStr())
}
}
}
jobChan <- job
}
// downloadAndSendImages will download dalle images and send them to the payer.
func (bot *TipBot) downloadAndSendImages(ctx context.Context, dalleClient dalle.Client, data dalle.GenerationData, event *InvoiceEvent) error {
reader, err := dalleClient.Download(ctx, data.ID)
if err != nil {
return err
}
defer reader.Close()
image := "data/dalle/" + data.ID + ".png"
file, err := os.Create(image)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(file, reader)
if err != nil {
return err
}
f, err := os.OpenFile(image, 0, os.ModePerm)
if err != nil {
return err
}
defer f.Close()
bot.trySendMessage(event.Payer.Telegram, &tb.Photo{File: tb.File{FileReader: f}})
return nil
}
func (bot *TipBot) dalleRefundUser(user *lnbits.User, message string) error {
if user.Wallet == nil {
return fmt.Errorf("user has no wallet")
}
me, err := GetUser(bot.Telegram.Me, *bot)
if err != nil {
return err
}
// create invioce for user
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Out: false,
Amount: int64(internal.Configuration.Generate.DallePrice),
Memo: fmt.Sprintf("Refund DALLE2 %s", user.GetUserStr()),
Webhook: internal.Configuration.Lnbits.WebhookServer},
bot.Client)
if err != nil {
return err
}
// pay invoice
_, err = me.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
if err != nil {
log.Errorln(err)
return err
}
log.Warnf("[DALLE] refunding user %s with %d sat", user.GetUserStr(), internal.Configuration.Generate.DallePrice)
var err_reason string
if len(message) > 0 {
err_reason = message
} else {
err_reason = "Something went wrong."
}
bot.trySendMessage(user.Telegram, fmt.Sprintf("🚫 %s You have been refunded.", err_reason))
return nil
}
+481
View File
@@ -0,0 +1,481 @@
package telegram
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/str"
log "github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
type Ticket struct {
Price int64 `json:"price"`
Memo string `json:"memo"`
Creator *lnbits.User `gorm:"embedded;embeddedPrefix:creator_"`
Cut int64 `json:"cut"` // Percent to cut from ticket price
BaseFee int64 `json:"base_fee"`
CutCheap int64 `json:"cut_cheap"` // Percent to cut from ticket price
BaseFeeCheap int64 `json:"base_fee_cheap"`
}
type Group struct {
Name string `json:"name"`
Title string `json:"title"`
ID int64 `json:"id" gorm:"primaryKey"`
Owner *tb.User `gorm:"embedded;embeddedPrefix:owner_"`
// Chat *tb.Chat `gorm:"embedded;embeddedPrefix:chat_"`
Ticket *Ticket `gorm:"embedded;embeddedPrefix:ticket_"`
}
type CreateChatInviteLink struct {
ChatID int64 `json:"chat_id"`
Name string `json:"name"`
ExpiryDate int `json:"expiry_date"`
MemberLimit int `json:"member_limit"`
CreatesJoinRequest bool `json:"creates_join_request"`
}
type Creator struct {
ID int64 `json:"id"`
IsBot bool `json:"is_bot"`
Firstname string `json:"first_name"`
Username string `json:"username"`
}
type Result struct {
InviteLink string `json:"invite_link"`
Name string `json:"name"`
Creator Creator `json:"creator"`
CreatesJoinRequest bool `json:"creates_join_request"`
IsPrimary bool `json:"is_primary"`
IsRevoked bool `json:"is_revoked"`
}
type ChatInviteLink struct {
Ok bool `json:"ok"`
Result Result `json:"result"`
}
type TicketEvent struct {
*storage.Base
*InvoiceEvent
Group *Group `gorm:"embedded;embeddedPrefix:group_"`
}
func (ticketEvent TicketEvent) Type() EventType {
return EventTypeTicketInvoice
}
func (ticketEvent TicketEvent) Key() string {
return ticketEvent.Base.ID
}
var (
ticketPayConfirmationMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
btnPayTicket = paymentConfirmationMenu.Data("✅ Pay", "pay_ticket")
)
var (
groupInvoiceMemo = "🎟 Ticket for group %s"
)
// groupHandler is called if the /group <cmd> command is invoked. It then decides with other
// handler to call depending on the <cmd> passed.
func (bot TipBot) groupHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
splits := strings.Split(m.Text, " ")
user := LoadUser(ctx)
if len(splits) == 1 {
if ctx.Message().Private() {
bot.trySendMessage(ctx.Message().Chat, fmt.Sprintf(Translate(ctx, "groupHelpMessage"), GetUserStr(bot.Telegram.Me), GetUserStr(bot.Telegram.Me)))
} else {
if bot.isOwner(ctx.Message().Chat, user.Telegram) {
bot.trySendMessage(ctx.Message().Chat, fmt.Sprintf(Translate(ctx, "commandPrivateMessage"), GetUserStr(bot.Telegram.Me)))
}
}
return ctx, nil
} else if len(splits) > 1 {
if splits[1] == "join" {
return bot.groupRequestJoinHandler(ctx)
}
if splits[1] == "add" {
return bot.addGroupHandler(ctx)
}
if splits[1] == "remove" {
// todo -- implement this
// return bot.addGroupHandler(ctx, m)
}
}
return ctx, nil
}
// groupRequestJoinHandler sends a payment request to the user who wants to join a group
func (bot TipBot) groupRequestJoinHandler(ctx intercept.Context) (intercept.Context, error) {
user := LoadUser(ctx)
// // reply only in private message
if ctx.Chat().Type != tb.ChatPrivate {
return ctx, fmt.Errorf("not private chat")
}
splits := strings.Split(ctx.Message().Text, " ")
// if the command was /group join
splitIdx := 1
// we also have the simpler command /join that can be used
// also by users who don't have an account with the bot yet
if splits[0] == "/join" {
splitIdx = 0
}
if len(splits) != splitIdx+2 || len(ctx.Message().Text) > 100 {
bot.trySendMessage(ctx.Message().Chat, Translate(ctx, "groupJoinGroupHelpMessage"))
return ctx, nil
}
groupName := strings.ToLower(splits[splitIdx+1])
group := &Group{}
tx := bot.DB.Groups.Where("name = ? COLLATE NOCASE", groupName).First(group)
if tx.Error != nil {
bot.trySendMessage(ctx.Message().Chat, Translate(ctx, "groupNotFoundMessage"))
return ctx, fmt.Errorf("group not found")
}
// create tickets
id := fmt.Sprintf("ticket:%d", group.ID)
invoiceEvent := &InvoiceEvent{
Base: storage.New(storage.ID(id)),
User: group.Ticket.Creator,
LanguageCode: ctx.Value("publicLanguageCode").(string),
Payer: user,
Chat: &tb.Chat{ID: group.ID},
CallbackData: id,
}
ticketEvent := &TicketEvent{
Base: storage.New(storage.ID(id)),
InvoiceEvent: invoiceEvent,
Group: group,
}
// if no price is set, then we don't need to pay
if group.Ticket.Price == 0 {
// save ticketevent for later
runtime.IgnoreError(ticketEvent.Set(ticketEvent, bot.Bunt))
bot.groupGetInviteLinkHandler(invoiceEvent)
return ctx, nil
}
// create an invoice
memo := fmt.Sprintf(groupInvoiceMemo, groupName)
var err error
invoiceEvent, err = bot.createGroupTicketInvoice(ctx, user, group, memo, InvoiceCallbackGroupTicket, id)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
log.Errorln(errmsg)
return ctx, err
}
ticketEvent.InvoiceEvent = invoiceEvent
// save ticketevent for later
defer ticketEvent.Set(ticketEvent, bot.Bunt)
// // if the user has enough balance, we send him a payment button
balance, err := bot.GetUserBalance(user)
if err != nil {
errmsg := fmt.Sprintf("[/group] Error: Could not get user balance: %s", err.Error())
log.Errorln(errmsg)
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "errorTryLaterMessage"))
return ctx, errors.New(errors.GetBalanceError, err)
}
if balance >= group.Ticket.Price {
return bot.groupSendPayButtonHandler(ctx, *ticketEvent)
}
// otherwise we send a payment request
// create qr code
qr, err := qrcode.Encode(invoiceEvent.PaymentRequest, qrcode.Medium, 256)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
log.Errorln(errmsg)
return ctx, err
}
ticketEvent.Message = bot.trySendMessage(ctx.Message().Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoiceEvent.PaymentRequest)})
bot.trySendMessage(ctx.Message().Sender, fmt.Sprintf(Translate(ctx, "groupPayInvoiceMessage"), groupName))
return ctx, nil
}
// groupSendPayButtonHandler is invoked if the user has enough balance so a message with a
// pay button is sent to the user.
func (bot *TipBot) groupSendPayButtonHandler(ctx intercept.Context, ticket TicketEvent) (intercept.Context, error) {
// object that holds all information about the send payment
// // // create inline buttons
btnPayTicket := ticketPayConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "pay_ticket", ticket.Base.ID)
ticketPayConfirmationMenu.Inline(
ticketPayConfirmationMenu.Row(
btnPayTicket),
)
confirmText := fmt.Sprintf(Translate(ctx, "confirmPayInvoiceMessage"), ticket.Group.Ticket.Price)
if len(ticket.Group.Ticket.Memo) > 0 {
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(ticket.Group.Ticket.Memo))
}
bot.trySendMessageEditable(ctx.Message().Chat, confirmText, ticketPayConfirmationMenu)
return ctx, nil
}
// groupConfirmPayButtonHandler is invoked if th user clicks the pay button.
func (bot *TipBot) groupConfirmPayButtonHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
tx := &TicketEvent{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.Bunt)
// immediatelly set intransaction to block duplicate calls
if err != nil {
log.Errorf("[groupConfirmPayButtonHandler] %s", err.Error())
return ctx, err
}
ticketEvent := sn.(*TicketEvent)
// onnly the correct user can press
if ticketEvent.Payer.Telegram.ID != c.Sender.ID {
return ctx, errors.Create(errors.UnknownError)
}
if !ticketEvent.Active {
log.Errorf("[confirmPayHandler] send not active anymore")
bot.tryEditMessage(c, i18n.Translate(ticketEvent.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
bot.tryDeleteMessage(c)
return ctx, errors.Create(errors.NotActiveError)
}
defer ticketEvent.Set(ticketEvent, bot.Bunt)
user := LoadUser(ctx)
if user.Wallet == nil {
bot.tryDeleteMessage(c)
return ctx, errors.Create(errors.UserNoWalletError)
}
log.Infof("[/pay] Attempting %s's invoice %s (%d sat)", user.GetUserStr(), ticketEvent.ID, ticketEvent.Group.Ticket.Price)
// // pay invoice
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: ticketEvent.Invoice.PaymentRequest}, bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of %s: %s", user.GetUserStr(), err)
err = fmt.Errorf(i18n.Translate(ticketEvent.LanguageCode, "invoiceUndefinedErrorMessage"))
bot.tryEditMessage(c, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
log.Errorln(errmsg)
return ctx, err
}
// update the message and remove the button
bot.tryEditMessage(c, i18n.Translate(ticketEvent.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
return ctx, nil
}
// groupGetInviteLinkHandler is called when the invoice is paid and sends a one-time group invite link to the payer
func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
invoiceEvent := event.(*InvoiceEvent)
// take a cut
// amount_bot := int64(ticketEvent.Group.Ticket.Price * int64(ticketEvent.Group.Ticket.Cut) / 100)
log.Infof(invoiceEvent.CallbackData)
ticketEvent := &TicketEvent{Base: storage.New(storage.ID(invoiceEvent.CallbackData))}
err := bot.Bunt.Get(ticketEvent)
if err != nil {
log.Errorf("[groupGetInviteLinkHandler] %s", err.Error())
return
}
log.Infof("[groupGetInviteLinkHandler] group: %d", ticketEvent.Chat.ID)
params := map[string]interface {
}{
"chat_id": ticketEvent.Group.ID, // must be the chat ID of the group
"name": fmt.Sprintf("%s link for %s", GetUserStr(bot.Telegram.Me), GetUserStr(ticketEvent.Payer.Telegram)), // the name of the invite link
"member_limit": 1, // only one user can join with this link
// "expire_date": time.Now().AddDate(0, 0, 1), // expiry date of the invite link, add one day
// "creates_join_request": false, // True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified
}
data, err := bot.Telegram.Raw("createChatInviteLink", params)
if err != nil {
return
}
var resp ChatInviteLink
if err := json.Unmarshal(data, &resp); err != nil {
return
}
if ticketEvent.Message != nil {
bot.tryDeleteMessage(ticketEvent.Message)
// do balance check for keyboard update
_, err = bot.GetUserBalance(ticketEvent.Payer)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", GetUserStr(ticketEvent.Payer.Telegram))
log.Errorln(errmsg)
}
bot.trySendMessage(ticketEvent.Payer.Telegram, i18n.Translate(ticketEvent.LanguageCode, "invoicePaidText"))
}
// send confirmation text with the ticket to the user
bot.trySendMessage(ticketEvent.Payer.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupClickToJoinMessage"), resp.Result.InviteLink, ticketEvent.Group.Title))
// send a notification to the group that sold the ticket
bot.trySendMessage(&tb.Chat{ID: ticketEvent.Group.ID}, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupTicketIssuedGroupMessage"), GetUserStrMd(ticketEvent.Payer.Telegram)))
// take a commission
ticketSat := ticketEvent.Group.Ticket.Price
if ticketEvent.Group.Ticket.Price > 20 {
me, err := GetUser(bot.Telegram.Me, *bot)
if err != nil {
log.Errorf("[groupGetInviteLinkHandler] Could not get bot user from DB: %s", err.Error())
return
}
// 2% cut + 100 sat base fee
commissionSat := ticketEvent.Group.Ticket.Price*ticketEvent.Group.Ticket.Cut/100 + ticketEvent.Group.Ticket.BaseFee
if ticketEvent.Group.Ticket.Price <= 1000 {
// if < 1000, then 10% cut + 10 sat base fee
commissionSat = ticketEvent.Group.Ticket.Price*ticketEvent.Group.Ticket.CutCheap/100 + ticketEvent.Group.Ticket.BaseFeeCheap
}
ticketSat = ticketEvent.Group.Ticket.Price - commissionSat
invoice, err := me.Wallet.Invoice(
lnbits.InvoiceParams{
Out: false,
Amount: commissionSat,
Memo: "🎟 Ticket commission for group " + ticketEvent.Group.Title,
Webhook: internal.Configuration.Lnbits.WebhookServer},
bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
log.Errorln(errmsg)
return
}
_, err = ticketEvent.User.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[groupGetInviteLinkHandler] Could not pay commission of %s: %s", GetUserStr(ticketEvent.User.Telegram), err)
log.Errorln(errmsg)
return
}
// do balance check for keyboard update
_, err = bot.GetUserBalance(ticketEvent.User)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", GetUserStr(ticketEvent.Payer.Telegram))
log.Errorln(errmsg)
}
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoiceCommission"), ticketSat, commissionSat, ticketEvent.Group.Title, GetUserStrMd(ticketEvent.Payer.Telegram)))
} else {
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoice"), ticketSat, ticketEvent.Group.Title, GetUserStrMd(ticketEvent.Payer.Telegram)))
}
}
// addGroupHandler is invoked if the user calls the "/group add" command
func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
if m.Chat.Type == tb.ChatPrivate {
bot.trySendMessage(m.Chat, Translate(ctx, "groupAddGroupHelpMessage"))
return ctx, fmt.Errorf("not in group")
}
// parse command "/group add <grou_name> [<amount>]"
splits := strings.Split(m.Text, " ")
if len(splits) < 3 || len(m.Text) > 100 {
bot.trySendMessage(m.Chat, Translate(ctx, "groupAddGroupHelpMessage"))
return ctx, nil
}
groupName := strings.ToLower(splits[2])
user := LoadUser(ctx)
// check if the user is the owner of the group
if !bot.isOwner(m.Chat, user.Telegram) {
return ctx, fmt.Errorf("not owner")
}
if !bot.isAdminAndCanInviteUsers(m.Chat, bot.Telegram.Me) {
bot.trySendMessage(m.Chat, Translate(ctx, "groupBotIsNotAdminMessage"))
return ctx, fmt.Errorf("bot is not admin")
}
// check if the group with this name is already in db
// only if a group with this name is owned by this user, it can be overwritten
group := &Group{}
tx := bot.DB.Groups.Where("name = ? COLLATE NOCASE", groupName).First(group)
if tx.Error == nil {
// if it is already added, check if this user is the admin
if user.Telegram.ID != group.Owner.ID || group.ID != m.Chat.ID {
bot.trySendMessage(m.Chat, Translate(ctx, "groupNameExists"))
return ctx, fmt.Errorf("not owner")
}
}
amount := int64(0) // default amount is zero
if amount_str, err := getArgumentFromCommand(m.Text, 3); err == nil {
amount, err = GetAmount(amount_str)
if err != nil {
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
return ctx, err
}
}
ticket := &Ticket{
Price: amount,
Memo: "Ticket for group " + groupName,
Creator: user,
Cut: 2,
BaseFee: 100,
CutCheap: 10,
BaseFeeCheap: 10,
}
group = &Group{
Name: groupName,
Title: m.Chat.Title,
ID: m.Chat.ID,
Owner: user.Telegram,
Ticket: ticket,
}
bot.DB.Groups.Save(group)
log.Infof("[group] Ticket of %d sat added to group %s.", group.Ticket.Price, group.Name)
bot.trySendMessage(m.Chat, fmt.Sprintf(Translate(ctx, "groupAddedMessage"), str.MarkdownEscape(m.Chat.Title), group.Name, group.Ticket.Price, GetUserStrMd(bot.Telegram.Me), group.Name))
return ctx, nil
}
// createGroupTicketInvoice produces an invoice for the group ticket with a
// callback that then calls groupGetInviteLinkHandler upton payment
func (bot *TipBot) createGroupTicketInvoice(ctx context.Context, payer *lnbits.User, group *Group, memo string, callback int, callbackData string) (*InvoiceEvent, error) {
invoice, err := group.Ticket.Creator.Wallet.Invoice(
lnbits.InvoiceParams{
Out: false,
Amount: group.Ticket.Price,
Memo: memo,
Webhook: internal.Configuration.Lnbits.WebhookServer},
bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
log.Errorln(errmsg)
return &InvoiceEvent{}, err
}
// save the invoice event
id := fmt.Sprintf("invoice:%s", invoice.PaymentHash)
invoiceEvent := &InvoiceEvent{
Base: storage.New(storage.ID(id)),
Invoice: &Invoice{PaymentHash: invoice.PaymentHash,
PaymentRequest: invoice.PaymentRequest,
Amount: group.Ticket.Price,
Memo: memo},
User: group.Ticket.Creator,
Callback: callback,
CallbackData: callbackData,
LanguageCode: ctx.Value("publicLanguageCode").(string),
Payer: payer,
Chat: &tb.Chat{ID: group.ID},
}
// add result to persistent struct
runtime.IgnoreError(invoiceEvent.Set(invoiceEvent, bot.Bunt))
return invoiceEvent, nil
}
File diff suppressed because it is too large Load Diff
+21 -19
View File
@@ -4,7 +4,9 @@ import (
"context"
"fmt"
tb "gopkg.in/lightningtipbot/telebot.v2"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
func (bot TipBot) makeHelpMessage(ctx context.Context, m *tb.Message) string {
@@ -26,25 +28,25 @@ func (bot TipBot) makeHelpMessage(ctx context.Context, m *tb.Message) string {
return fmt.Sprintf(helpMessage, dynamicHelpMessage)
}
func (bot TipBot) helpHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
func (bot TipBot) helpHandler(ctx intercept.Context) (intercept.Context, error) {
// check and print all commands
bot.anyTextHandler(ctx, m)
if !m.Private() {
bot.anyTextHandler(ctx)
if !ctx.Message().Private() {
// delete message
bot.tryDeleteMessage(m)
bot.tryDeleteMessage(ctx.Message())
}
bot.trySendMessage(m.Sender, bot.makeHelpMessage(ctx, m), tb.NoPreview)
bot.trySendMessage(ctx.Sender(), bot.makeHelpMessage(ctx, ctx.Message()), tb.NoPreview)
return ctx, nil
}
func (bot TipBot) basicsHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
func (bot TipBot) basicsHandler(ctx intercept.Context) (intercept.Context, error) {
// check and print all commands
bot.anyTextHandler(ctx, m)
if !m.Private() {
bot.anyTextHandler(ctx)
if !ctx.Message().Private() {
// delete message
bot.tryDeleteMessage(m)
bot.tryDeleteMessage(ctx.Message())
}
bot.trySendMessage(m.Sender, Translate(ctx, "basicsMessage"), tb.NoPreview)
bot.trySendMessage(ctx.Sender(), Translate(ctx, "basicsMessage"), tb.NoPreview)
return ctx, nil
}
@@ -59,11 +61,11 @@ func (bot TipBot) makeAdvancedHelpMessage(ctx context.Context, m *tb.Message) st
// we print the anonymous ln address in the advanced help
lnaddr, err := bot.UserGetAnonLightningAddress(fromUser)
if err == nil {
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Anonymous lightning address: `%s`\n", lnaddr)
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Anonymous Lightning address: `%s`\n", lnaddr)
}
lnurl, err := UserGetLNURL(fromUser)
lnurl, err := UserGetAnonLNURL(fromUser)
if err == nil {
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("LNURL: `%s`", lnurl)
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Anonymous LNURL: `%s`", lnurl)
}
// this is so stupid:
@@ -74,13 +76,13 @@ func (bot TipBot) makeAdvancedHelpMessage(ctx context.Context, m *tb.Message) st
)
}
func (bot TipBot) advancedHelpHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
func (bot TipBot) advancedHelpHandler(ctx intercept.Context) (intercept.Context, error) {
// check and print all commands
bot.anyTextHandler(ctx, m)
if !m.Private() {
bot.anyTextHandler(ctx)
if !ctx.Message().Private() {
// delete message
bot.tryDeleteMessage(m)
bot.tryDeleteMessage(ctx.Message())
}
bot.trySendMessage(m.Sender, bot.makeAdvancedHelpMessage(ctx, m), tb.NoPreview)
bot.trySendMessage(ctx.Sender(), bot.makeAdvancedHelpMessage(ctx, ctx.Message()), tb.NoPreview)
return ctx, nil
}
+37 -32
View File
@@ -7,18 +7,20 @@ import (
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
i18n2 "github.com/nicksnyder/go-i18n/v2/i18n"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
const queryImage = "https://avatars.githubusercontent.com/u/88730856?v=4"
const queryImage = "https://avatars.githubusercontent.com/u/88730856?v=7"
func (bot TipBot) inlineQueryInstructions(ctx context.Context, q *tb.Query) (context.Context, error) {
func (bot TipBot) inlineQueryInstructions(ctx intercept.Context) (intercept.Context, error) {
instructions := []struct {
url string
title string
@@ -60,11 +62,11 @@ func (bot TipBot) inlineQueryInstructions(ctx context.Context, q *tb.Query) (con
results[i].SetResultID(strconv.Itoa(i))
}
err := bot.Telegram.Answer(q, &tb.QueryResponse{
err := ctx.Answer(&tb.QueryResponse{
Results: results,
CacheTime: 5, // a minute
IsPersonal: true,
QueryID: q.ID,
QueryID: ctx.Query().ID,
})
if err != nil {
@@ -73,7 +75,7 @@ func (bot TipBot) inlineQueryInstructions(ctx context.Context, q *tb.Query) (con
return ctx, err
}
func (bot TipBot) inlineQueryReplyWithError(q *tb.Query, message string, help string) {
func (bot TipBot) inlineQueryReplyWithError(ctx intercept.Context, message string, help string) {
results := make(tb.Results, 1) // []tb.Result
result := &tb.ArticleResult{
// URL: url,
@@ -83,11 +85,12 @@ func (bot TipBot) inlineQueryReplyWithError(q *tb.Query, message string, help st
// required for photos
ThumbURL: queryImage,
}
id := fmt.Sprintf("inl-error-%d-%s", q.From.ID, RandStringRunes(5))
id := fmt.Sprintf("inl-error-%d-%s", ctx.Query().Sender.ID, RandStringRunes(5))
result.SetResultID(id)
results[0] = result
err := bot.Telegram.Answer(q, &tb.QueryResponse{
Results: results,
err := ctx.Answer(&tb.QueryResponse{
Results: results,
CacheTime: 1, // 60 == 1 minute, todo: make higher than 1 s in production
})
@@ -98,21 +101,22 @@ 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) {
func (bot TipBot) anyChosenInlineHandler(ctx intercept.Context) (intercept.Context, error) {
// load inline object from cache
inlineObject, err := bot.Cache.Get(q.ResultID)
inlineObject, err := bot.Cache.Get(ctx.InlineResult().ResultID)
// check error
if err != nil {
log.Errorf("[anyChosenInlineHandler] could not find inline object in cache. %v", err.Error())
return
return ctx, err
}
switch inlineObject.(type) {
case storage.Storable:
// persist inline object in bunt
runtime.IgnoreError(bot.Bunt.Set(inlineObject.(storage.Storable)))
default:
log.Errorf("[anyChosenInlineHandler] invalid inline object type: %s, query: %s", reflect.TypeOf(inlineObject).String(), q.Query)
log.Errorf("[anyChosenInlineHandler] invalid inline object type: %s, query: %s", reflect.TypeOf(inlineObject).String(), ctx.InlineResult().Query)
}
return ctx, nil
}
func (bot TipBot) commandTranslationMap(ctx context.Context, command string) context.Context {
@@ -134,36 +138,37 @@ func (bot TipBot) commandTranslationMap(ctx context.Context, command string) con
return ctx
}
func (bot TipBot) anyQueryHandler(ctx context.Context, q *tb.Query) (context.Context, error) {
if q.Text == "" {
return bot.inlineQueryInstructions(ctx, q)
func (bot TipBot) anyQueryHandler(ctx intercept.Context) (intercept.Context, error) {
if ctx.Query().Text == "" {
return bot.inlineQueryInstructions(ctx)
}
// create the inline send result
if strings.HasPrefix(q.Text, "/") {
q.Text = strings.TrimPrefix(q.Text, "/")
var text = ctx.Query().Text
if strings.HasPrefix(text, "/") {
text = strings.TrimPrefix(text, "/")
}
if strings.HasPrefix(q.Text, "send") || strings.HasPrefix(q.Text, "pay") {
return bot.handleInlineSendQuery(ctx, q)
if strings.HasPrefix(text, "send") || strings.HasPrefix(text, "pay") {
return bot.handleInlineSendQuery(ctx)
}
if strings.HasPrefix(q.Text, "faucet") || strings.HasPrefix(q.Text, "zapfhahn") || strings.HasPrefix(q.Text, "kraan") || strings.HasPrefix(q.Text, "grifo") {
if len(strings.Split(q.Text, " ")) > 1 {
c := strings.Split(q.Text, " ")[0]
ctx = bot.commandTranslationMap(ctx, c)
if strings.HasPrefix(text, "faucet") || strings.HasPrefix(text, "zapfhahn") || strings.HasPrefix(text, "kraan") || strings.HasPrefix(text, "grifo") {
if len(strings.Split(text, " ")) > 1 {
c := strings.Split(text, " ")[0]
ctx.Context = bot.commandTranslationMap(ctx, c)
}
return bot.handleInlineFaucetQuery(ctx, q)
return bot.handleInlineFaucetQuery(ctx)
}
if strings.HasPrefix(q.Text, "tipjar") || strings.HasPrefix(q.Text, "spendendose") {
if len(strings.Split(q.Text, " ")) > 1 {
c := strings.Split(q.Text, " ")[0]
ctx = bot.commandTranslationMap(ctx, c)
if strings.HasPrefix(text, "tipjar") || strings.HasPrefix(text, "spendendose") {
if len(strings.Split(text, " ")) > 1 {
c := strings.Split(text, " ")[0]
ctx.Context = bot.commandTranslationMap(ctx, c)
}
return bot.handleInlineTipjarQuery(ctx, q)
return bot.handleInlineTipjarQuery(ctx)
}
if strings.HasPrefix(q.Text, "receive") || strings.HasPrefix(q.Text, "get") || strings.HasPrefix(q.Text, "payme") || strings.HasPrefix(q.Text, "request") {
return bot.handleInlineReceiveQuery(ctx, q)
if strings.HasPrefix(text, "receive") || strings.HasPrefix(text, "get") || strings.HasPrefix(text, "payme") || strings.HasPrefix(text, "request") {
return bot.handleInlineReceiveQuery(ctx)
}
return ctx, nil
}
+44 -42
View File
@@ -8,6 +8,7 @@ import (
"time"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
@@ -20,11 +21,11 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
var (
inlineReceiveMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
inlineReceiveMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
btnCancelInlineReceive = inlineReceiveMenu.Data("🚫 Cancel", "cancel_receive_inline")
btnAcceptInlineReceive = inlineReceiveMenu.Data("💸 Pay", "confirm_receive_inline")
)
@@ -32,7 +33,7 @@ var (
type InlineReceive struct {
*storage.Base
MessageText string `json:"inline_receive_messagetext"`
Message *tb.Message `json:"inline_receive_message"`
Message tb.Editable `json:"inline_receive_message"`
Amount int64 `json:"inline_receive_amount"`
From *lnbits.User `json:"inline_receive_from"`
To *lnbits.User `json:"inline_receive_to"`
@@ -42,7 +43,7 @@ type InlineReceive struct {
}
func (bot TipBot) makeReceiveKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
inlineReceiveMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
inlineReceiveMenu := &tb.ReplyMarkup{ResizeKeyboard: true}
acceptInlineReceiveButton := inlineReceiveMenu.Data(Translate(ctx, "payReceiveButtonMessage"), "confirm_receive_inline")
cancelInlineReceiveButton := inlineReceiveMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_receive_inline")
acceptInlineReceiveButton.Data = id
@@ -56,18 +57,19 @@ func (bot TipBot) makeReceiveKeyboard(ctx context.Context, id string) *tb.ReplyM
return inlineReceiveMenu
}
func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) (context.Context, error) {
func (bot TipBot) handleInlineReceiveQuery(ctx intercept.Context) (intercept.Context, error) {
q := ctx.Query()
to := LoadUser(ctx)
amount, err := decodeAmountFromCommand(q.Text)
if err != nil {
bot.inlineQueryReplyWithError(q, Translate(ctx, "inlineQueryReceiveTitle"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
bot.inlineQueryReplyWithError(ctx, Translate(ctx, "inlineQueryReceiveTitle"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
return ctx, err
}
if amount < 1 {
bot.inlineQueryReplyWithError(q, Translate(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
bot.inlineQueryReplyWithError(ctx, Translate(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
return ctx, errors.Create(errors.InvalidAmountError)
}
toUserStrMd := GetUserStrMd(&q.From)
toUserStr := GetUserStr(q.Sender)
// check whether the 3rd argument is a username
// command is "@LightningTipBot receive 123 @from_user This is the memo"
@@ -81,7 +83,7 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) (co
if err != nil {
//bot.tryDeleteMessage(m)
//bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), toUserStrMention))
bot.inlineQueryReplyWithError(q,
bot.inlineQueryReplyWithError(ctx,
fmt.Sprintf(TranslateUser(ctx, "sendUserHasNoWalletMessage"), from_username),
fmt.Sprintf(TranslateUser(ctx, "inlineQueryReceiveDescription"),
bot.Telegram.Me.Username))
@@ -99,7 +101,7 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) (co
}
results := make(tb.Results, len(urls)) // []tb.Result
for i, url := range urls {
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineReceiveMessage"), toUserStrMd, amount)
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineReceiveMessage"), toUserStr, amount)
// modify message if payment is to specific user
if from_SpecificUser {
@@ -117,8 +119,8 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) (co
// required for photos
ThumbURL: url,
}
id := fmt.Sprintf("inl:receive:%d:%d:%s", q.From.ID, amount, RandStringRunes(5))
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeReceiveKeyboard(ctx, id).InlineKeyboard}
id := fmt.Sprintf("inl-receive-%d-%d-%s", q.Sender.ID, amount, RandStringRunes(5))
result.ReplyMarkup = &tb.ReplyMarkup{InlineKeyboard: bot.makeReceiveKeyboard(ctx, id).InlineKeyboard}
results[i] = result
// needed to set a unique string ID for each result
results[i].SetResultID(id)
@@ -148,7 +150,8 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) (co
return ctx, nil
}
func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
func (bot *TipBot) acceptInlineReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
// immediatelly set intransaction to block duplicate calls
mutex.LockWithContext(ctx, tx.ID)
@@ -161,7 +164,6 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callbac
inlineReceive := rn.(*InlineReceive)
if !inlineReceive.Active {
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveCancelledMessage"), &tb.ReplyMarkup{})
return ctx, errors.Create(errors.NotActiveError)
}
@@ -179,7 +181,7 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callbac
inlineReceive.From = from
}
inlineReceive.Message = c.Message
inlineReceive.Message = c
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
to := inlineReceive.To
@@ -197,15 +199,17 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callbac
if from.Wallet == nil || balance < inlineReceive.Amount {
// if user has no wallet, show invoice
bot.tryEditMessage(inlineReceive.Message, inlineReceive.MessageText, &tb.ReplyMarkup{})
return bot.inlineReceiveInvoice(ctx, c, inlineReceive)
// runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
bot.inlineReceiveInvoice(ctx, inlineReceive)
return ctx, errors.Create(errors.BalanceToLowError)
} else {
// else, do an internal transaction
return bot.sendInlineReceiveHandler(ctx, c)
return bot.sendInlineReceiveHandler(ctx)
}
}
func (bot *TipBot) sendInlineReceiveHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
func (bot *TipBot) sendInlineReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
@@ -219,7 +223,6 @@ func (bot *TipBot) sendInlineReceiveHandler(ctx context.Context, c *tb.Callback)
if !inlineReceive.Active {
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveCancelledMessage"), &tb.ReplyMarkup{})
return ctx, errors.Create(errors.NotActiveError)
}
@@ -248,35 +251,35 @@ func (bot *TipBot) sendInlineReceiveHandler(ctx context.Context, c *tb.Callback)
inlineReceive.Inactivate(inlineReceive, bot.Bunt)
// todo: user new get username function to get userStrings
transactionMemo := fmt.Sprintf("InlineReceive from %s to %s (%d sat).", fromUserStr, toUserStr, inlineReceive.Amount)
transactionMemo := fmt.Sprintf("💸 Receive from %s to %s.", fromUserStr, toUserStr)
t := NewTransaction(bot, from, to, inlineReceive.Amount, TransactionType("inline receive"))
t.Memo = transactionMemo
success, err := t.Send()
if !success {
errMsg := fmt.Sprintf("[acceptInlineReceiveHandler] Transaction failed: %s", err.Error())
log.Errorln(errMsg)
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveFailedMessage"), &tb.ReplyMarkup{})
bot.tryEditMessage(c, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveFailedMessage"), &tb.ReplyMarkup{})
return ctx, errors.Create(errors.UnknownError)
}
log.Infof("[💸 inlineReceive] Send from %s to %s (%d sat).", fromUserStr, toUserStr, inlineReceive.Amount)
inlineReceive.Set(inlineReceive, bot.Bunt)
return bot.finishInlineReceiveHandler(ctx, c)
ctx.Context, err = bot.finishInlineReceiveHandler(ctx, ctx.Callback())
return ctx, err
}
func (bot *TipBot) inlineReceiveInvoice(ctx context.Context, c *tb.Callback, inlineReceive *InlineReceive) (context.Context, error) {
func (bot *TipBot) inlineReceiveInvoice(ctx intercept.Context, inlineReceive *InlineReceive) {
if !inlineReceive.Active {
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveCancelledMessage"), &tb.ReplyMarkup{})
return ctx, errors.Create(errors.NotActiveError)
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 ctx, err
return
}
// create qr code
@@ -285,23 +288,19 @@ func (bot *TipBot) inlineReceiveInvoice(ctx context.Context, c *tb.Callback, inl
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 ctx, err
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))
}
msg := bot.trySendMessage(ctx.Callback().Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
bot.tryEditMessage(inlineReceive.Message, fmt.Sprintf("%s\n\nPay this invoice:\n```%s```", inlineReceive.MessageText, invoice.PaymentRequest))
invoice.InvoiceMessage = msg
runtime.IgnoreError(bot.Bunt.Set(invoice))
log.Printf("[/invoice] Incvoice created. User: %s, amount: %d sat.", GetUserStr(inlineReceive.To.Telegram), inlineReceive.Amount)
return ctx, nil
}
func (bot *TipBot) inlineReceiveEvent(invoiceEvent *InvoiceEvent) {
func (bot *TipBot) inlineReceiveEvent(event Event) {
invoiceEvent := event.(*InvoiceEvent)
bot.tryDeleteMessage(invoiceEvent.InvoiceMessage)
bot.notifyInvoiceReceivedEvent(invoiceEvent)
bot.finishInlineReceiveHandler(nil, &tb.Callback{Data: string(invoiceEvent.CallbackData)})
@@ -310,8 +309,10 @@ func (bot *TipBot) inlineReceiveEvent(invoiceEvent *InvoiceEvent) {
func (bot *TipBot) finishInlineReceiveHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
// immediatelly set intransaction to block duplicate calls
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
if ctx != nil {
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
}
rn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[getInlineReceive] %s", err.Error())
@@ -324,7 +325,7 @@ func (bot *TipBot) finishInlineReceiveHandler(ctx context.Context, c *tb.Callbac
toUserStrMd := GetUserStrMd(to.Telegram)
fromUserStrMd := GetUserStrMd(from.Telegram)
toUserStr := GetUserStr(to.Telegram)
inlineReceive.MessageText = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendUpdateMessageAccept"), inlineReceive.Amount, fromUserStrMd, toUserStrMd))
inlineReceive.MessageText = fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendUpdateMessageAccept"), inlineReceive.Amount, fromUserStrMd, toUserStrMd)
memo := inlineReceive.Memo
if len(memo) > 0 {
inlineReceive.MessageText += fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveAppendMemo"), memo)
@@ -347,7 +348,8 @@ func (bot *TipBot) finishInlineReceiveHandler(ctx context.Context, c *tb.Callbac
// inlineReceive.Release(inlineReceive, bot.Bunt)
}
func (bot *TipBot) cancelInlineReceiveHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
func (bot *TipBot) cancelInlineReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
@@ -361,7 +363,7 @@ func (bot *TipBot) cancelInlineReceiveHandler(ctx context.Context, c *tb.Callbac
if c.Sender.ID != inlineReceive.To.Telegram.ID {
return ctx, errors.Create(errors.UnknownError)
}
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveCancelledMessage"), &tb.ReplyMarkup{})
bot.tryEditMessage(c, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveCancelledMessage"), &tb.ReplyMarkup{})
// set the inlineReceive inactive
inlineReceive.Active = false
return ctx, inlineReceive.Set(inlineReceive, bot.Bunt)
+100 -39
View File
@@ -7,6 +7,7 @@ import (
"time"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
@@ -18,11 +19,11 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
var (
inlineSendMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
inlineSendMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
btnCancelInlineSend = inlineSendMenu.Data("🚫 Cancel", "cancel_send_inline")
btnAcceptInlineSend = inlineSendMenu.Data("✅ Receive", "confirm_send_inline")
)
@@ -39,7 +40,7 @@ type InlineSend struct {
}
func (bot TipBot) makeSendKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
inlineSendMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
inlineSendMenu := &tb.ReplyMarkup{ResizeKeyboard: true}
acceptInlineSendButton := inlineSendMenu.Data(Translate(ctx, "receiveButtonMessage"), "confirm_send_inline")
cancelInlineSendButton := inlineSendMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_send_inline")
acceptInlineSendButton.Data = id
@@ -53,31 +54,36 @@ func (bot TipBot) makeSendKeyboard(ctx context.Context, id string) *tb.ReplyMark
return inlineSendMenu
}
func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) (context.Context, error) {
func (bot TipBot) handleInlineSendQuery(ctx intercept.Context) (intercept.Context, error) {
q := ctx.Query()
// inlineSend := NewInlineSend()
// var err error
amount, err := decodeAmountFromCommand(q.Text)
if err != nil {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQuerySendTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQuerySendTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
return ctx, err
}
if amount < 1 {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
return ctx, errors.Create(errors.InvalidAmountError)
}
fromUser := LoadUser(ctx)
fromUserStr := GetUserStr(&q.From)
fromUserStrMd := GetUserStrMd(&q.From)
fromUserStr := GetUserStr(q.Sender)
balance, err := bot.GetUserBalanceCached(fromUser)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
log.Errorln(errmsg)
log.WithFields(log.Fields{
"module": "telegram",
"func": "handleInlineSendQuery"}).Errorln(errmsg)
return ctx, err
}
// check if fromUser has balance
if balance < amount {
log.Errorf("Balance of user %s too low", fromUserStr)
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
log.WithFields(log.Fields{
"module": "telegram",
"func": "handleInlineSendQuery",
"user": fromUserStr}).Errorf("Balance too low")
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
return ctx, errors.Create(errors.InvalidAmountError)
}
@@ -93,7 +99,7 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) (conte
if err != nil {
//bot.tryDeleteMessage(m)
//bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), toUserStrMention))
bot.inlineQueryReplyWithError(q,
bot.inlineQueryReplyWithError(ctx,
fmt.Sprintf(TranslateUser(ctx, "sendUserHasNoWalletMessage"), to_username),
fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"),
bot.Telegram.Me.Username))
@@ -111,7 +117,7 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) (conte
}
results := make(tb.Results, len(urls)) // []tb.Result
for i, url := range urls {
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineSendMessage"), fromUserStrMd, amount)
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineSendMessage"), fromUserStr, amount)
// modify message if payment is to specific user
if to_SpecificUser {
@@ -129,8 +135,8 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) (conte
// required for photos
ThumbURL: url,
}
id := fmt.Sprintf("inl:send:%d:%d:%s", q.From.ID, amount, RandStringRunes(5))
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeSendKeyboard(ctx, id).InlineKeyboard}
id := fmt.Sprintf("inl-send-%d-%d-%s", q.Sender.ID, amount, RandStringRunes(5))
result.ReplyMarkup = &tb.ReplyMarkup{InlineKeyboard: bot.makeSendKeyboard(ctx, id).InlineKeyboard}
results[i] = result
// needed to set a unique string ID for each result
results[i].SetResultID(id)
@@ -157,13 +163,20 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) (conte
})
if err != nil {
log.Errorln(err)
log.WithFields(log.Fields{
"module": "telegram",
"func": "handleInlineSendQuery",
"user": fromUserStr,
"user_id": fromUser.ID,
"wallet_id": fromUser.Wallet.ID,
"telegram_id": fromUser.Telegram.ID}).Errorln(err)
return ctx, err
}
return ctx, nil
}
func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
func (bot *TipBot) acceptInlineSendHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
to := LoadUser(ctx)
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
@@ -178,9 +191,13 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
fromUser := inlineSend.From
if !inlineSend.Active {
log.Errorf("[acceptInlineSendHandler] inline send not active anymore")
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
return ctx, errors.Create(errors.NotActiveError)
err = errors.Create(errors.NotActiveError)
log.WithFields(log.Fields{
"module": "inline_send",
"func": "acceptInlineSendHandler",
"error": err.Error()},
).Errorf("inline send not active anymore")
return ctx, err
}
defer inlineSend.Set(inlineSend, bot.Bunt)
@@ -211,11 +228,26 @@ func (bot *TipBot) acceptInlineSendHandler(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("[sendInline] User %s has no wallet.", toUserStr)
log.WithFields(log.Fields{
"module": "inline_send",
"func": "acceptInlineSendHandler",
"to_user": toUserStr,
"to_user_id": to.ID,
"user": fromUserStr,
"user_id": fromUser.ID,
"wallet_id": fromUser.Wallet.ID},
).Infof("User has no wallet.")
to, err = bot.CreateWalletForTelegramUser(to.Telegram)
if err != nil {
errmsg := fmt.Errorf("[sendInline] Error: Could not create wallet for %s", toUserStr)
log.Errorln(errmsg)
log.WithFields(log.Fields{
"module": "inline_send",
"func": "acceptInlineSendHandler",
"to_user": toUserStr,
"user": fromUserStr,
"user_id": fromUser.ID,
"wallet_id": fromUser.Wallet.ID,
"error": err.Error()},
).Errorln("Could not create wallet for user")
return ctx, err
}
}
@@ -223,18 +255,45 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
inlineSend.Inactivate(inlineSend, bot.Bunt)
// todo: user new get username function to get userStrings
transactionMemo := fmt.Sprintf("InlineSend from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
transactionMemo := fmt.Sprintf("💸 Send from %s to %s.", fromUserStr, toUserStr)
t := NewTransaction(bot, fromUser, to, amount, TransactionType("inline send"))
t.Memo = transactionMemo
success, err := t.Send()
if !success {
errMsg := fmt.Sprintf("[sendInline] Transaction failed: %s", err.Error())
log.Errorln(errMsg)
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "inlineSendFailedMessage"), &tb.ReplyMarkup{})
return ctx, errors.Create(errors.UnknownError)
if err != nil {
log.WithFields(log.Fields{
"module": "inline_send",
"func": "acceptInlineSendHandler",
"to_user": toUserStr,
"to_user_id": to.ID,
"to_wallet_id": to.Wallet.ID,
"user": fromUserStr,
"user_id": fromUser.ID,
"wallet_id": fromUser.Wallet.ID,
"amount": amount,
"error": err.Error()},
).Errorln("inline send failed")
}
log.Infof("[💸 sendInline] Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
if !success {
err = errors.Create(errors.UnknownError)
log.WithFields(log.Fields{
"module": "inline_send",
"func": "acceptInlineSendHandler",
"error": err.Error()},
).Errorln("transaction failed")
bot.tryEditMessage(c, i18n.Translate(inlineSend.LanguageCode, "inlineSendFailedMessage"), &tb.ReplyMarkup{})
return ctx, err
}
log.WithFields(log.Fields{
"module": "inline_send",
"func": "acceptInlineSendHandler",
"to_user": toUserStr,
"to_user_id": to.ID,
"to_wallet_id": to.Wallet.ID,
"user": fromUserStr,
"user_id": fromUser.ID,
"wallet_id": fromUser.Wallet.ID,
"amount": amount},
).Infof("Success")
inlineSend.Message = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineSend.LanguageCode, "inlineSendUpdateMessageAccept"), amount, fromUserStrMd, toUserStrMd))
memo := inlineSend.Memo
@@ -244,32 +303,34 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
if !to.Initialized {
inlineSend.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineSend.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
}
bot.tryEditMessage(c.Message, inlineSend.Message, &tb.ReplyMarkup{})
bot.tryEditMessage(c, inlineSend.Message, &tb.ReplyMarkup{})
// notify users
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
bot.trySendMessage(fromUser.Telegram, fmt.Sprintf(i18n.Translate(fromUser.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[sendInline] Error: Send message to %s: %s", toUserStr, err)
log.Warnln(errmsg)
}
return ctx, nil
}
func (bot *TipBot) cancelInlineSendHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
func (bot *TipBot) cancelInlineSendHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
// immediatelly set intransaction to block duplicate calls
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[cancelInlineSendHandler] %s", err.Error())
log.WithFields(log.Fields{
"module": "inline_send",
"func": "cancelInlineSendHandler",
"error": err.Error()},
).Errorf("could not cancel")
return ctx, err
}
inlineSend := sn.(*InlineSend)
if c.Sender.ID != inlineSend.From.Telegram.ID {
return ctx, errors.Create(errors.UnknownError)
}
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
bot.tryEditMessage(c, i18n.Translate(inlineSend.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
// set the inlineSend inactive
inlineSend.Active = false
return ctx, inlineSend.Set(inlineSend, bot.Bunt)
-77
View File
@@ -1,77 +0,0 @@
package intercept
import (
"context"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type CallbackFuncHandler func(ctx context.Context, message *tb.Callback) (context.Context, error)
type Func func(ctx context.Context, message interface{}) (context.Context, error)
type handlerCallbackInterceptor struct {
handler CallbackFuncHandler
before CallbackChain
after CallbackChain
onDefer CallbackChain
}
type CallbackChain []Func
type CallbackInterceptOption func(*handlerCallbackInterceptor)
func WithBeforeCallback(chain ...Func) CallbackInterceptOption {
return func(a *handlerCallbackInterceptor) {
a.before = chain
}
}
func WithAfterCallback(chain ...Func) CallbackInterceptOption {
return func(a *handlerCallbackInterceptor) {
a.after = chain
}
}
func WithDeferCallback(chain ...Func) CallbackInterceptOption {
return func(a *handlerCallbackInterceptor) {
a.onDefer = chain
}
}
func interceptCallback(ctx context.Context, message *tb.Callback, hm CallbackChain) (context.Context, error) {
if ctx == nil {
ctx = context.Background()
}
if hm != nil {
var err error
for _, m := range hm {
ctx, err = m(ctx, message)
if err != nil {
return ctx, err
}
}
}
return ctx, nil
}
func HandlerWithCallback(handler CallbackFuncHandler, option ...CallbackInterceptOption) func(Callback *tb.Callback) {
hm := &handlerCallbackInterceptor{handler: handler}
for _, opt := range option {
opt(hm)
}
return func(c *tb.Callback) {
ctx := context.Background()
ctx, err := interceptCallback(ctx, c, hm.before)
if err != nil {
log.Traceln(err)
return
}
defer interceptCallback(ctx, c, hm.onDefer)
ctx, err = hm.handler(ctx, c)
if err != nil {
log.Traceln(err)
return
}
_, err = interceptCallback(ctx, c, hm.after)
if err != nil {
log.Traceln(err)
}
}
}
+114
View File
@@ -0,0 +1,114 @@
package intercept
import (
"context"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// Context bundles tb.Context and context.Context
type Context struct {
context.Context
TeleContext
}
// TeleContext is a proxy struct for tb.Context
type TeleContext struct {
tb.Context
}
// Func is the custom intercept handler func type. This will accept and return the bundled context
type Func func(ctx Context) (Context, error)
// handlerWithInterceptor is the custom handler func containing a Chain of intercept's
type handlerWithInterceptor struct {
handler Func
before Chain
after Chain
onDefer Chain
fields log.Fields
}
// Chain are multiple custom intercept Func
type Chain []Func
// Option for building custom intercept Chain
type Option func(*handlerWithInterceptor)
func WithBefore(chain ...Func) Option {
return func(a *handlerWithInterceptor) {
a.before = chain
}
}
func WithAfter(chain ...Func) Option {
return func(a *handlerWithInterceptor) {
a.after = chain
}
}
func WithDefer(chain ...Func) Option {
return func(a *handlerWithInterceptor) {
a.onDefer = chain
}
}
func WithDefaultLogFields(f log.Fields) Option {
return func(a *handlerWithInterceptor) {
a.fields = f
}
}
// intercept is where all intercept's from single Chain are executed
func intercept(ctx Context, chain Chain) (Context, error) {
if chain != nil {
var err error
for _, m := range chain {
ctx, err = m(ctx)
if err != nil {
return ctx, err
}
}
}
return ctx, nil
}
// WithHandler returns a tb.HandlerFunc and which will proxy the real handler.
func WithHandler(handler Func, option ...Option) tb.HandlerFunc {
// create handlerWithInterceptor
hm := &handlerWithInterceptor{handler: handler}
for _, opt := range option {
opt(hm)
}
// return proxy handler
return func(c tb.Context) error {
h := Context{TeleContext: TeleContext{Context: c}, Context: context.Background()}
// add default log fields from handler to context
if len(hm.fields) > 0 {
h.Context = context.WithValue(h.Context, "fields", hm.fields)
}
// add uuid for log tracing to context
h.Context = context.WithValue(h.Context, "uuid", uuid.New().String())
// run all before intercepts
h, err := intercept(h, hm.before)
if err != nil {
log.Traceln(err)
return err
}
// make sure to run onDefer intercepts
defer intercept(h, hm.onDefer)
// run the real handler
h, err = hm.handler(h)
if err != nil {
log.Traceln(err)
return err
}
// run all after intercepts
_, err = intercept(h, hm.after)
if err != nil {
log.Traceln(err)
return err
}
return nil
}
}
-77
View File
@@ -1,77 +0,0 @@
package intercept
import (
"context"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type MessageFuncHandler func(ctx context.Context, message *tb.Message) (context.Context, error)
type handlerMessageInterceptor struct {
handler MessageFuncHandler
before MessageChain
after MessageChain
onDefer MessageChain
}
type MessageChain []Func
type MessageInterceptOption func(*handlerMessageInterceptor)
func WithBeforeMessage(chain ...Func) MessageInterceptOption {
return func(a *handlerMessageInterceptor) {
a.before = chain
}
}
func WithAfterMessage(chain ...Func) MessageInterceptOption {
return func(a *handlerMessageInterceptor) {
a.after = chain
}
}
func WithDeferMessage(chain ...Func) MessageInterceptOption {
return func(a *handlerMessageInterceptor) {
a.onDefer = chain
}
}
func interceptMessage(ctx context.Context, message *tb.Message, hm MessageChain) (context.Context, error) {
if ctx == nil {
ctx = context.Background()
}
if hm != nil {
var err error
for _, m := range hm {
ctx, err = m(ctx, message)
if err != nil {
return ctx, err
}
}
}
return ctx, nil
}
func HandlerWithMessage(handler MessageFuncHandler, option ...MessageInterceptOption) func(message *tb.Message) {
hm := &handlerMessageInterceptor{handler: handler}
for _, opt := range option {
opt(hm)
}
return func(message *tb.Message) {
ctx := context.Background()
ctx, err := interceptMessage(ctx, message, hm.before)
if err != nil {
log.Traceln(err)
return
}
defer interceptMessage(ctx, message, hm.onDefer)
ctx, err = hm.handler(ctx, message)
if err != nil {
log.Traceln(err)
return
}
_, err = interceptMessage(ctx, message, hm.after)
if err != nil {
log.Traceln(err)
return
}
}
}
-77
View File
@@ -1,77 +0,0 @@
package intercept
import (
"context"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type QueryFuncHandler func(ctx context.Context, message *tb.Query) (context.Context, error)
type handlerQueryInterceptor struct {
handler QueryFuncHandler
before QueryChain
after QueryChain
onDefer QueryChain
}
type QueryChain []Func
type QueryInterceptOption func(*handlerQueryInterceptor)
func WithBeforeQuery(chain ...Func) QueryInterceptOption {
return func(a *handlerQueryInterceptor) {
a.before = chain
}
}
func WithAfterQuery(chain ...Func) QueryInterceptOption {
return func(a *handlerQueryInterceptor) {
a.after = chain
}
}
func WithDeferQuery(chain ...Func) QueryInterceptOption {
return func(a *handlerQueryInterceptor) {
a.onDefer = chain
}
}
func interceptQuery(ctx context.Context, message *tb.Query, hm QueryChain) (context.Context, error) {
if ctx == nil {
ctx = context.Background()
}
if hm != nil {
var err error
for _, m := range hm {
ctx, err = m(ctx, message)
if err != nil {
return ctx, err
}
}
}
return ctx, nil
}
func HandlerWithQuery(handler QueryFuncHandler, option ...QueryInterceptOption) func(message *tb.Query) {
hm := &handlerQueryInterceptor{handler: handler}
for _, opt := range option {
opt(hm)
}
return func(query *tb.Query) {
ctx := context.Background()
ctx, err := interceptQuery(context.Background(), query, hm.before)
if err != nil {
log.Traceln(err)
return
}
defer interceptQuery(ctx, query, hm.onDefer)
ctx, err = hm.handler(ctx, query)
if err != nil {
log.Traceln(err)
return
}
_, err = interceptQuery(ctx, query, hm.after)
if err != nil {
log.Traceln(err)
return
}
}
}
+118 -113
View File
@@ -3,7 +3,7 @@ package telegram
import (
"context"
"fmt"
"reflect"
"github.com/LightningTipBot/LightningTipBot/internal/log"
"strconv"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
@@ -16,20 +16,12 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type InterceptorType int
const (
MessageInterceptor InterceptorType = iota
CallbackInterceptor
QueryInterceptor
logrus "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
type Interceptor struct {
Type InterceptorType
Fields logrus.Fields
Before []intercept.Func
After []intercept.Func
OnDefer []intercept.Func
@@ -37,43 +29,43 @@ type Interceptor struct {
// singletonClickInterceptor uses the onceMap to determine whether the object k1 already interacted
// with the user k2. If so, it will return an error.
func (bot TipBot) singletonCallbackInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
switch i.(type) {
case *tb.Callback:
c := i.(*tb.Callback)
return ctx, once.Once(c.Data, strconv.FormatInt(c.Sender.ID, 10))
func (bot TipBot) singletonCallbackInterceptor(ctx intercept.Context) (intercept.Context, error) {
if ctx.Callback() != nil {
return ctx, once.Once(ctx.Callback().Data, strconv.FormatInt(ctx.Callback().Sender.ID, 10))
}
return ctx, errors.Create(errors.InvalidTypeError)
}
// lockInterceptor invoked as first before interceptor
func (bot TipBot) lockInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
user := getTelegramUserFromInterface(i)
func (bot TipBot) lockInterceptor(ctx intercept.Context) (intercept.Context, error) {
user := ctx.Sender()
if user != nil {
mutex.Lock(strconv.FormatInt(user.ID, 10))
return ctx, nil
}
return nil, errors.Create(errors.InvalidTypeError)
return ctx, errors.Create(errors.InvalidTypeError)
}
// unlockInterceptor invoked as onDefer interceptor
func (bot TipBot) unlockInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
user := getTelegramUserFromInterface(i)
func (bot TipBot) unlockInterceptor(ctx intercept.Context) (intercept.Context, error) {
user := ctx.Sender()
if user != nil {
mutex.Unlock(strconv.FormatInt(user.ID, 10))
return ctx, nil
}
return ctx, errors.Create(errors.InvalidTypeError)
}
func (bot TipBot) idInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
return context.WithValue(ctx, "uid", RandStringRunes(64)), nil
// idInterceptor wraps random uid into context
func (bot TipBot) idInterceptor(ctx intercept.Context) (intercept.Context, error) {
ctx.Context = context.WithValue(ctx, "uid", RandStringRunes(64))
return ctx, nil
}
// answerCallbackInterceptor will answer the callback with the given text in the context
func (bot TipBot) answerCallbackInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
switch i.(type) {
case *tb.Callback:
c := i.(*tb.Callback)
func (bot TipBot) answerCallbackInterceptor(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
if c != nil {
ctxcr := ctx.Value("callback_response")
var res []*tb.CallbackResponse
if ctxcr != nil {
@@ -92,58 +84,70 @@ func (bot TipBot) answerCallbackInterceptor(ctx context.Context, i interface{})
// 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) {
func (bot TipBot) requireUserInterceptor(ctx intercept.Context) (intercept.Context, error) {
var user *lnbits.User
var err error
u := getTelegramUserFromInterface(i)
u := ctx.Sender()
if u != nil {
user, err = GetUser(u, bot)
// do not respond to banned users
if bot.UserIsBanned(user) {
ctx = context.WithValue(ctx, "banned", true)
return context.WithValue(ctx, "user", user), errors.Create(errors.InvalidTypeError)
ctx.Context = context.WithValue(ctx, "banned", true)
ctx.Context = context.WithValue(ctx, "user", user)
return ctx, errors.Create(errors.InvalidTypeError)
}
if user != nil {
return context.WithValue(ctx, "user", user), err
ctx.Context = context.WithValue(ctx, "user", user)
return ctx, err
}
}
return nil, errors.Create(errors.InvalidTypeError)
return ctx, errors.Create(errors.InvalidTypeError)
}
func (bot TipBot) loadUserInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
ctx, _ = bot.requireUserInterceptor(ctx, i)
// startUserInterceptor will invoke /start if user not exists.
func (bot TipBot) startUserInterceptor(ctx intercept.Context) (intercept.Context, error) {
handler, err := bot.loadUserInterceptor(ctx)
if err != nil {
// user banned
return handler, err
}
// load user
u := ctx.Value("user")
// check user nil
if u != nil {
user := u.(*lnbits.User)
// check wallet nil or !initialized
if user.Wallet == nil || !user.Initialized {
handler, err = bot.startHandler(handler)
if err != nil {
return handler, err
}
return handler, nil
}
}
return handler, nil
}
// loadUserInterceptor will try to wrap user into context. Returns error if user is banned
func (bot TipBot) loadUserInterceptor(ctx intercept.Context) (intercept.Context, error) {
ctx, _ = bot.requireUserInterceptor(ctx)
// if user is banned, also loadUserInterceptor will return an error
if ctx.Value("banned") != nil && ctx.Value("banned").(bool) {
return nil, errors.Create(errors.InvalidTypeError)
return ctx, errors.Create(errors.InvalidTypeError)
}
return ctx, nil
}
// getTelegramUserFromInterface returns the tb user based in interface type
func getTelegramUserFromInterface(i interface{}) (user *tb.User) {
switch i.(type) {
case *tb.Query:
user = &i.(*tb.Query).From
case *tb.Callback:
user = i.(*tb.Callback).Sender
case *tb.Message:
user = i.(*tb.Message).Sender
default:
log.Tracef("[getTelegramUserFromInterface] invalid type %s", reflect.TypeOf(i).String())
}
return
}
// loadReplyToInterceptor Loading the Telegram user with message intercept
func (bot TipBot) loadReplyToInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
switch i.(type) {
case *tb.Message:
m := i.(*tb.Message)
if m.ReplyTo != nil {
if m.ReplyTo.Sender != nil {
user, _ := GetUser(m.ReplyTo.Sender, bot)
user.Telegram = m.ReplyTo.Sender
return context.WithValue(ctx, "reply_to_user", user), nil
func (bot TipBot) loadReplyToInterceptor(ctx intercept.Context) (intercept.Context, error) {
if ctx.Message() != nil {
if ctx.Message().ReplyTo != nil {
if ctx.Message().ReplyTo.Sender != nil {
user, _ := GetUser(ctx.Message().ReplyTo.Sender, bot)
user.Telegram = ctx.Message().ReplyTo.Sender
ctx.Context = context.WithValue(ctx, "reply_to_user", user)
return ctx, nil
}
}
return ctx, nil
@@ -151,75 +155,76 @@ func (bot TipBot) loadReplyToInterceptor(ctx context.Context, i interface{}) (co
return ctx, errors.Create(errors.InvalidTypeError)
}
func (bot TipBot) localizerInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
// localizerInterceptor will wrap localizer into context, based on user settings.
func (bot TipBot) localizerInterceptor(ctx intercept.Context) (intercept.Context, error) {
var userLocalizer *i18n2.Localizer
var publicLocalizer *i18n2.Localizer
// default language is english
publicLocalizer = i18n2.NewLocalizer(i18n.Bundle, "en")
ctx = context.WithValue(ctx, "publicLanguageCode", "en")
ctx = context.WithValue(ctx, "publicLocalizer", publicLocalizer)
ctx.Context = context.WithValue(ctx, "publicLanguageCode", "en")
ctx.Context = context.WithValue(ctx, "publicLocalizer", publicLocalizer)
switch i.(type) {
case *tb.Message:
m := i.(*tb.Message)
userLocalizer = i18n2.NewLocalizer(i18n.Bundle, m.Sender.LanguageCode)
ctx = context.WithValue(ctx, "userLanguageCode", m.Sender.LanguageCode)
ctx = context.WithValue(ctx, "userLocalizer", userLocalizer)
if m.Private() {
if ctx.Message() != nil {
userLocalizer = i18n2.NewLocalizer(i18n.Bundle, ctx.Message().Sender.LanguageCode)
ctx.Context = context.WithValue(ctx, "userLanguageCode", ctx.Message().Sender.LanguageCode)
ctx.Context = context.WithValue(ctx, "userLocalizer", userLocalizer)
if ctx.Message().Private() {
// in pm overwrite public localizer with user localizer
ctx = context.WithValue(ctx, "publicLanguageCode", m.Sender.LanguageCode)
ctx = context.WithValue(ctx, "publicLocalizer", userLocalizer)
ctx.Context = context.WithValue(ctx, "publicLanguageCode", ctx.Message().Sender.LanguageCode)
ctx.Context = context.WithValue(ctx, "publicLocalizer", userLocalizer)
}
return ctx, nil
case *tb.Callback:
m := i.(*tb.Callback)
userLocalizer = i18n2.NewLocalizer(i18n.Bundle, m.Sender.LanguageCode)
ctx = context.WithValue(ctx, "userLanguageCode", m.Sender.LanguageCode)
return context.WithValue(ctx, "userLocalizer", userLocalizer), nil
case *tb.Query:
m := i.(*tb.Query)
userLocalizer = i18n2.NewLocalizer(i18n.Bundle, m.From.LanguageCode)
ctx = context.WithValue(ctx, "userLanguageCode", m.From.LanguageCode)
return context.WithValue(ctx, "userLocalizer", userLocalizer), nil
} else if ctx.Callback() != nil {
userLocalizer = i18n2.NewLocalizer(i18n.Bundle, ctx.Callback().Sender.LanguageCode)
ctx.Context = context.WithValue(ctx, "userLanguageCode", ctx.Callback().Sender.LanguageCode)
ctx.Context = context.WithValue(ctx, "userLocalizer", userLocalizer)
return ctx, nil
} else if ctx.Query() != nil {
userLocalizer = i18n2.NewLocalizer(i18n.Bundle, ctx.Query().Sender.LanguageCode)
ctx.Context = context.WithValue(ctx, "userLanguageCode", ctx.Query().Sender.LanguageCode)
ctx.Context = context.WithValue(ctx, "userLocalizer", userLocalizer)
return ctx, nil
}
return ctx, nil
}
// requirePrivateChatInterceptor will ensure, that handler was invoked in private chat.
func (bot TipBot) requirePrivateChatInterceptor(ctx intercept.Context) (intercept.Context, error) {
if ctx.Chat().Type != tb.ChatPrivate {
return ctx, fmt.Errorf("[requirePrivateChatInterceptor] no private chat")
}
return ctx, nil
}
func (bot TipBot) requirePrivateChatInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
switch i.(type) {
case *tb.Message:
m := i.(*tb.Message)
if m.Chat.Type != tb.ChatPrivate {
return nil, fmt.Errorf("[requirePrivateChatInterceptor] no private chat")
// logMessageInterceptor will log incoming handler requests.
func (bot TipBot) logMessageInterceptor(ctx intercept.Context) (intercept.Context, error) {
user := LoadUser(ctx)
if user == nil {
user = &lnbits.User{Telegram: ctx.Sender()}
}
if ctx.Message() != nil {
// log incoming messages
if ctx.Message().Text != "" {
log.WithObjects(ctx, user).WithFields(logrus.Fields{
"module": "telegram",
"func": "logMessageInterceptor"}).Infof("intercepting message")
} else if ctx.Message().Photo != nil {
log.WithObjects(ctx, user).WithFields(logrus.Fields{
"module": "telegram",
"func": "logMessageInterceptor"}).Infof("intercepting photo message")
}
return ctx, nil
}
return nil, errors.Create(errors.InvalidTypeError)
}
const photoTag = "<Photo>"
func (bot TipBot) logMessageInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
switch i.(type) {
case *tb.Message:
m := i.(*tb.Message)
if m.Text != "" {
log_string := fmt.Sprintf("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
if m.IsReply() {
log_string = fmt.Sprintf("%s -> %s", log_string, GetUserStr(m.ReplyTo.Sender))
}
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)
}
return ctx, nil
case *tb.Callback:
m := i.(*tb.Callback)
log.Infof("[Callback %s:%d] Data: %s", GetUserStr(m.Sender), m.Sender.ID, m.Data)
} else if ctx.Callback() != nil {
// log incoming callbacks
log.WithObjects(ctx, user).WithFields(logrus.Fields{
"module": "telegram",
"func": "logMessageInterceptor"}).Infof("intercepting callback")
return ctx, nil
}
return nil, errors.Create(errors.InvalidTypeError)
return ctx, errors.Create(errors.InvalidTypeError)
}
// LoadUser from context
+78 -28
View File
@@ -4,32 +4,44 @@ import (
"bytes"
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/log"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal"
log "github.com/sirupsen/logrus"
"github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/skip2/go-qrcode"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
type InvoiceEventCallback map[int]func(*InvoiceEvent)
type InvoiceEventCallback map[int]EventHandler
type EventHandler struct {
Function func(event Event)
Type EventType
}
var InvoiceCallback InvoiceEventCallback
func initInvoiceEventCallbacks(bot *TipBot) {
InvoiceCallback = InvoiceEventCallback{
InvoiceCallbackGeneric: bot.notifyInvoiceReceivedEvent,
InvoiceCallbackInlineReceive: bot.inlineReceiveEvent,
InvoiceCallbackLNURLPayReceive: bot.lnurlReceiveEvent,
InvoiceCallbackGeneric: EventHandler{Function: bot.notifyInvoiceReceivedEvent, Type: EventTypeInvoice},
InvoiceCallbackInlineReceive: EventHandler{Function: bot.inlineReceiveEvent, Type: EventTypeInvoice},
InvoiceCallbackLNURLPayReceive: EventHandler{Function: bot.lnurlReceiveEvent, Type: EventTypeInvoice},
InvoiceCallbackGroupTicket: EventHandler{Function: bot.groupGetInviteLinkHandler, Type: EventTypeInvoice},
InvoiceCallbackSatdressProxy: EventHandler{Function: bot.satdressProxyRelayPaymentHandler, Type: EventTypeInvoice},
InvoiceCallbackGenerateDalle: EventHandler{Function: bot.generateDalleImages, Type: EventTypeInvoice},
}
}
@@ -39,8 +51,25 @@ const (
InvoiceCallbackGeneric = iota + 1
InvoiceCallbackInlineReceive
InvoiceCallbackLNURLPayReceive
InvoiceCallbackGroupTicket
InvoiceCallbackSatdressProxy
InvoiceCallbackGenerateDalle
)
const (
EventTypeInvoice EventType = "invoice"
EventTypeTicketInvoice EventType = "ticket-invoice"
)
type EventType string
func AssertEventType(event Event, eventType EventType) error {
if event.Type() != eventType {
return fmt.Errorf("invalid event type")
}
return nil
}
type Invoice struct {
PaymentHash string `json:"payment_hash"`
PaymentRequest string `json:"payment_request"`
@@ -49,12 +78,23 @@ type Invoice struct {
}
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"`
*storage.Base
User *lnbits.User `json:"user"` // the user that is being paid
Message *tb.Message `json:"message,omitempty"` // the message that the invoice replies to
InvoiceMessage *tb.Message `json:"invoice_message,omitempty"` // the message that displays the invoice
LanguageCode string `json:"languagecode"` // language code of the user
Callback int `json:"func"` // which function to call if the invoice is paid
CallbackData string `json:"callbackdata"` // add some data for the callback
Chat *tb.Chat `json:"chat,omitempty"` // if invoice is supposed to be sent to a particular chat
Payer *lnbits.User `json:"payer,omitempty"` // if a particular user is supposed to pay this
}
func (invoiceEvent InvoiceEvent) Type() EventType {
return EventTypeInvoice
}
type Event interface {
Type() EventType
}
func (invoiceEvent InvoiceEvent) Key() string {
@@ -69,14 +109,20 @@ func helpInvoiceUsage(ctx context.Context, errormsg string) string {
}
}
func (bot *TipBot) invoiceHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
// check and print all commands
bot.anyTextHandler(ctx, m)
bot.anyTextHandler(ctx)
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
userStr := GetUserStr(user.Telegram)
logfields := logrus.Fields{
"module": "telegram",
"func": "invoiceHandler",
"path": "/invoice"}
if m.Chat.Type != tb.ChatPrivate {
// delete message
bot.tryDeleteMessage(m)
@@ -103,21 +149,21 @@ func (bot *TipBot) invoiceHandler(ctx context.Context, m *tb.Message) (context.C
}
creatingMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
log.Debugf("[/invoice] Creating invoice for %s of %d sat.", userStr, amount)
logfields["amount"] = amount
log.WithObjects(ctx, user).WithFields(logfields).Debugf("Creating 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)
log.WithObjects(ctx, user, err).WithFields(logfields).Errorln(errmsg)
return ctx, err
}
logfields["invoice"] = invoice.PaymentRequest
// 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)
log.WithObjects(ctx, user, err).WithFields(logfields).Errorln("Failed to create QR code for invoice")
return ctx, err
}
@@ -126,7 +172,7 @@ func (bot *TipBot) invoiceHandler(ctx context.Context, m *tb.Message) (context.C
// 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)
log.WithObjects(ctx, user).WithFields(logfields).Printf("Incvoice created.")
return ctx, nil
}
@@ -134,13 +180,14 @@ func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Out: false,
Amount: int64(amount),
Amount: amount,
Memo: memo,
Webhook: internal.Configuration.Lnbits.WebhookServer},
bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
log.Errorln(errmsg)
log.WithObjects(ctx, user, err).WithFields(logrus.Fields{
"module": "telegram",
"func": "createInvoiceWithEvent"}).Errorln("Could not create an invoice")
return InvoiceEvent{}, err
}
invoiceEvent := InvoiceEvent{
@@ -158,12 +205,13 @@ func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User
return invoiceEvent, nil
}
func (bot *TipBot) notifyInvoiceReceivedEvent(invoiceEvent *InvoiceEvent) {
func (bot *TipBot) notifyInvoiceReceivedEvent(event Event) {
invoiceEvent := event.(*InvoiceEvent)
// do balance check for keyboard update
_, err := bot.GetUserBalance(invoiceEvent.User)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", GetUserStr(invoiceEvent.User.Telegram))
log.Errorln(errmsg)
log.WithObjects(invoiceEvent.User, err).WithFields(logrus.Fields{"module": "telegram", "func": "notifyInvoiceReceivedEvent"}).Error(errmsg)
}
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
@@ -183,11 +231,13 @@ func (lnurlInvoice LNURLInvoice) Key() string {
return fmt.Sprintf("lnurl-p:%s", lnurlInvoice.PaymentHash)
}
func (bot *TipBot) lnurlReceiveEvent(invoiceEvent *InvoiceEvent) {
func (bot *TipBot) lnurlReceiveEvent(event Event) {
invoiceEvent := event.(*InvoiceEvent)
bot.notifyInvoiceReceivedEvent(invoiceEvent)
tx := &LNURLInvoice{Invoice: &Invoice{PaymentHash: invoiceEvent.PaymentHash}}
err := bot.Bunt.Get(tx)
log.Debugf("[lnurl-p] Received invoice for %s of %d sat.", GetUserStr(invoiceEvent.User.Telegram), tx.Amount)
log.WithObjects(tx.User, err).WithFields(logrus.Fields{"module": "lnurl", "func": "lnurlReceiveEvent", "amount": tx.Amount}).Debugf("Received invoice")
if err == nil {
if len(tx.Comment) > 0 {
if len(tx.From) == 0 {
+22 -23
View File
@@ -2,38 +2,27 @@ package telegram
import (
"bytes"
"context"
"fmt"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal"
log "github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
func (bot *TipBot) lndhubHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
if internal.Configuration.Lnbits.LnbitsPublicUrl == "" {
bot.trySendMessage(m.Sender, Translate(ctx, "couldNotLinkMessage"))
return ctx, fmt.Errorf("invalid configuration")
}
// check and print all commands
bot.anyTextHandler(ctx, m)
// reply only in private message
if m.Chat.Type != tb.ChatPrivate {
// delete message
bot.tryDeleteMessage(m)
}
// first check whether the user is initialized
fromUser := LoadUser(ctx)
bot.trySendMessage(m.Sender, Translate(ctx, "walletConnectMessage"))
// do not respond to banned users
if bot.UserIsBanned(fromUser) {
log.Warnln("[lndhubHandler] user is banned. not responding.")
return ctx, fmt.Errorf("user is banned")
}
linkmsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "walletConnectMessage"))
lndhubUrl := fmt.Sprintf("lndhub://admin:%s@%slndhub/ext/", fromUser.Wallet.Adminkey, internal.Configuration.Lnbits.LnbitsPublicUrl)
@@ -46,14 +35,24 @@ func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) (context.Co
}
// 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)})
qrmsg := bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
// auto delete
go func() {
time.Sleep(time.Second * 60)
bot.tryDeleteMessage(linkmsg)
bot.trySendMessage(m.Sender, Translate(ctx, "linkHiddenMessage"))
bot.tryDeleteMessage(qrmsg)
bot.tryEditMessage(linkmsg, Translate(ctx, "linkHiddenMessage"), tb.Silent)
}()
return ctx, nil
}
func (bot *TipBot) apiHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
fromUser := LoadUser(ctx)
apimesg := bot.trySendMessageEditable(m.Sender, fmt.Sprintf(Translate(ctx, "apiConnectMessage"), fromUser.Wallet.Adminkey, fromUser.Wallet.Inkey))
// auto delete
go func() {
time.Sleep(time.Second * 60)
bot.tryEditMessage(apimesg, Translate(ctx, "apiHiddenMessage"))
}()
// auto delete the message
// NewMessage(linkmsg, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
return ctx, nil
}
+26 -19
View File
@@ -6,6 +6,9 @@ import (
"fmt"
"net/url"
"github.com/LightningTipBot/LightningTipBot/internal/network"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
@@ -17,11 +20,11 @@ import (
lnurl "github.com/fiatjaf/go-lnurl"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
var (
authConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
authConfirmationMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
btnCancelAuth = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_login")
btnAuth = paymentConfirmationMenu.Data("✅ Login", "confirm_login")
)
@@ -37,19 +40,17 @@ type LnurlAuthState struct {
// lnurlPayHandler1 is invoked when the first lnurl response was a lnurlpay response
// at this point, the user hans't necessarily entered an amount yet
func (bot *TipBot) lnurlAuthHandler(ctx context.Context, m *tb.Message, authParams LnurlAuthState) (context.Context, error) {
func (bot *TipBot) lnurlAuthHandler(ctx context.Context, m *tb.Message, authParams *LnurlAuthState) (context.Context, error) {
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
// object that holds all information about the send payment
id := fmt.Sprintf("lnurlauth-%d-%s", m.Sender.ID, RandStringRunes(5))
lnurlAuthState := &LnurlAuthState{
Base: storage.New(storage.ID(id)),
From: user,
LNURLAuthParams: authParams.LNURLAuthParams,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
authParams.Base = storage.New(storage.ID(id))
authParams.From = user
authParams.LanguageCode = ctx.Value("publicLanguageCode").(string)
// // // create inline buttons
btnAuth = paymentConfirmationMenu.Data(Translate(ctx, "loginButtonMessage"), "confirm_login", id)
btnCancelAuth = paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_login", id)
@@ -59,19 +60,20 @@ func (bot *TipBot) lnurlAuthHandler(ctx context.Context, m *tb.Message, authPara
btnAuth,
btnCancelAuth),
)
lnurlAuthState.Message = bot.trySendMessageEditable(m.Chat,
authParams.Message = bot.trySendMessageEditable(m.Chat,
fmt.Sprintf(Translate(ctx, "confirmLnurlAuthMessager"),
lnurlAuthState.LNURLAuthParams.CallbackURL.Host,
authParams.LNURLAuthParams.CallbackURL.Host,
),
paymentConfirmationMenu,
)
// save to bunt
runtime.IgnoreError(lnurlAuthState.Set(lnurlAuthState, bot.Bunt))
runtime.IgnoreError(authParams.Set(authParams, bot.Bunt))
return ctx, nil
}
func (bot *TipBot) confirmLnurlAuthHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
func (bot *TipBot) confirmLnurlAuthHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
tx := &LnurlAuthState{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
@@ -95,7 +97,7 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx context.Context, c *tb.Callback)
// statusMsg := bot.trySendMessageEditable(c.Sender,
// Translate(ctx, "lnurlResolvingUrlMessage"),
// )
bot.editSingleButton(ctx, c.Message, lnurlAuthState.Message.Text, Translate(ctx, "lnurlResolvingUrlMessage"))
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlAuthState.Message.Text, ButtonText: Translate(ctx, "lnurlResolvingUrlMessage")})
// from fiatjaf/go-lnurl
p := lnurlAuthState.LNURLAuthParams
@@ -105,7 +107,7 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx context.Context, c *tb.Callback)
}
var sentsigres lnurl.LNURLResponse
client, err := bot.GetHttpClient()
client, err := network.GetClient(network.ClientTypeClearNet)
if err != nil {
return ctx, err
}
@@ -120,15 +122,20 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx context.Context, c *tb.Callback)
return ctx, err
}
if sentsigres.Status == "ERROR" {
bot.tryEditMessage(c.Message, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), sentsigres.Reason))
bot.tryEditMessage(c, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), sentsigres.Reason))
return ctx, err
}
bot.editSingleButton(ctx, c.Message, lnurlAuthState.Message.Text, Translate(ctx, "lnurlSuccessfulLogin"))
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{
Message: lnurlAuthState.Message.Text,
ButtonText: Translate(ctx, "lnurlSuccessfulLogin"),
URL: fmt.Sprintf("https://%s", lnurlAuthState.LNURLAuthParams.Host),
})
return ctx, lnurlAuthState.Inactivate(lnurlAuthState, bot.Bunt)
}
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
func (bot *TipBot) cancelLnurlAuthHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
func (bot *TipBot) cancelLnurlAuthHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
tx := &LnurlAuthState{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
@@ -145,7 +152,7 @@ func (bot *TipBot) cancelLnurlAuthHandler(ctx context.Context, c *tb.Callback) (
return ctx, errors.Create(errors.UnknownError)
}
// delete and send instead of edit for the keyboard to pop up after sending
bot.tryEditMessage(c.Message, i18n.Translate(lnurlAuthState.LanguageCode, "loginCancelledMessage"), &tb.ReplyMarkup{})
bot.tryEditMessage(c, i18n.Translate(lnurlAuthState.LanguageCode, "loginCancelledMessage"), &tb.ReplyMarkup{})
// bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"), &tb.ReplyMarkup{})
return ctx, lnurlAuthState.Inactivate(lnurlAuthState, bot.Bunt)
}
+131 -50
View File
@@ -9,6 +9,9 @@ import (
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/network"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
@@ -18,35 +21,33 @@ import (
lnurl "github.com/fiatjaf/go-lnurl"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
// LnurlPayState saves the state of the user for an LNURL payment
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"`
From *lnbits.User `json:"from"`
LNURLPayParams lnurl.LNURLPayParams `json:"LNURLPayParams"`
LNURLPayValues lnurl.LNURLPayValues `json:"LNURLPayValues"`
Amount int64 `json:"amount"`
Comment string `json:"comment"`
DescriptionHash string `json:"descriptionHash,omitempty"`
LanguageCode string `json:"languagecode"`
}
// lnurlPayHandler1 is invoked when the first lnurl response was a lnurlpay response
// lnurlPayHandler is invoked when the first lnurl response was a lnurlpay response
// at this point, the user hans't necessarily entered an amount yet
func (bot *TipBot) lnurlPayHandler(ctx context.Context, m *tb.Message, payParams LnurlPayState) {
func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPayState) (context.Context, error) {
m := ctx.Message()
user := LoadUser(ctx)
if user.Wallet == nil {
return
return ctx, fmt.Errorf("user has no wallet")
}
// object that holds all information about the send payment
id := fmt.Sprintf("lnurlp-%d-%s", m.Sender.ID, RandStringRunes(5))
lnurlPayState := &LnurlPayState{
Base: storage.New(storage.ID(id)),
From: user,
LNURLPayParams: payParams.LNURLPayParams,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
payParams.Base = storage.New(storage.ID(id))
payParams.From = user
payParams.LanguageCode = ctx.Value("publicLanguageCode").(string)
// first we check whether an amount is present in the command
amount, amount_err := decodeAmountFromCommand(m.Text)
@@ -61,52 +62,73 @@ func (bot *TipBot) lnurlPayHandler(ctx context.Context, m *tb.Message, payParams
// 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) > int(payParams.LNURLPayParams.CommentAllowed) {
memo = memo[:payParams.LNURLPayParams.CommentAllowed]
}
if len(memo) > 0 {
lnurlPayState.Comment = memo
payParams.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
(int64(amount) > (payParams.LNURLPayParams.MaxSendable/1000) || int64(amount) < (payParams.LNURLPayParams.MinSendable/1000)) &&
(payParams.LNURLPayParams.MaxSendable != 0 && payParams.LNURLPayParams.MinSendable != 0) { // only if max and min are set
err := fmt.Errorf("amount not in range")
log.Warnf("[lnurlPayHandler] Error: %s", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), lnurlPayState.LNURLPayParams.MinSendable/1000, lnurlPayState.LNURLPayParams.MaxSendable/1000))
log.WithFields(log.Fields{
"module": "telegram",
"func": "lnurlPayHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID}).Warnf("%s", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), payParams.LNURLPayParams.MinSendable/1000, payParams.LNURLPayParams.MaxSendable/1000))
ResetUserState(user, bot)
return
return ctx, err
}
// set also amount in the state of the user
lnurlPayState.Amount = amount * 1000 // save as mSat
payParams.Amount = amount * 1000 // save as mSat
// calculate description hash of the metadata and save it
descriptionHash, err := bot.DescriptionHash(payParams.LNURLPayParams.Metadata, "")
if err != nil {
return nil, err
}
payParams.DescriptionHash = descriptionHash
// add result to persistent struct
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
runtime.IgnoreError(payParams.Set(payParams, bot.Bunt))
// now we actualy check whether the amount was in the command and if not, ask for it
if amount_err != nil || amount < 1 {
if payParams.LNURLPayParams.MinSendable == payParams.LNURLPayParams.MaxSendable {
amount = payParams.LNURLPayParams.MaxSendable / 1000
payParams.Amount = amount * 1000 // save as mSat
} else if amount_err != nil || amount < 1 {
// // no amount was entered, set user state and ask for amount
bot.askForAmount(ctx, id, "LnurlPayState", lnurlPayState.LNURLPayParams.MinSendable, lnurlPayState.LNURLPayParams.MaxSendable, m.Text)
return
bot.askForAmount(ctx, id, "LnurlPayState", payParams.LNURLPayParams.MinSendable, payParams.LNURLPayParams.MaxSendable, m.Text)
return ctx, nil
}
// We need to save the pay state in the user state so we can load the payment in the next handler
paramsJson, err := json.Marshal(lnurlPayState)
// We need to save the pay state in the user state so we can load the payment in the next ctx
paramsJson, err := json.Marshal(payParams)
if err != nil {
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
log.WithFields(log.Fields{
"module": "telegram",
"func": "lnurlPayHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID}).Errorf(err.Error())
// bot.trySendMessage(m.Sender, err.Error())
return
return ctx, err
}
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
// directly go to confirm
bot.lnurlPayHandlerSend(ctx, m)
return
bot.lnurlPayHandlerSend(ctx)
return ctx, nil
}
// 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) (context.Context, error) {
func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
@@ -115,7 +137,12 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) (cont
// assert that user has entered an amount
if user.StateKey != lnbits.UserHasEnteredAmount {
log.Errorln("[lnurlPayHandlerSend] state keys don't match")
log.WithFields(log.Fields{
"module": "telegram",
"func": "lnurlPayHandlerSend",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID}).Errorln("state keys don't match")
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return ctx, fmt.Errorf("wrong state key")
}
@@ -124,7 +151,12 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) (cont
var enterAmountData EnterAmountStateData
err := json.Unmarshal([]byte(user.StateData), &enterAmountData)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
log.WithFields(log.Fields{
"module": "telegram",
"func": "lnurlPayHandlerSend",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID}).Errorf("Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
@@ -134,7 +166,12 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) (cont
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
log.WithFields(log.Fields{
"module": "telegram",
"func": "lnurlPayHandlerSend",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID}).Errorf(err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
@@ -142,15 +179,25 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) (cont
// LnurlPayState loaded
client, err := bot.GetHttpClient()
client, err := network.GetClient(network.ClientTypeClearNet)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
log.WithFields(log.Fields{
"module": "telegram",
"func": "lnurlPayHandlerSend",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID}).Errorf(err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
log.WithFields(log.Fields{
"module": "telegram",
"func": "lnurlPayHandlerSend",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID}).Errorf(err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
@@ -166,13 +213,23 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) (cont
res, err := client.Get(callbackUrl.String())
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
log.WithFields(log.Fields{
"module": "telegram",
"func": "lnurlPayHandlerSend",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID}).Errorf(err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
log.WithFields(log.Fields{
"module": "telegram",
"func": "lnurlPayHandlerSend",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID}).Errorf(err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
@@ -184,20 +241,45 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) (cont
if len(response2.Reason) > 0 {
error_reason = response2.Reason
}
log.Errorf("[lnurlPayHandler] Error in LNURLPayValues: %s", error_reason)
log.WithFields(log.Fields{
"module": "telegram",
"func": "lnurlPayHandlerSend",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"telegram_id": user.Telegram.ID,
"error": error_reason}).Error("Error in LNURLPayValues")
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
return ctx, fmt.Errorf("Error in LNURLPayValues: %s", error_reason)
return ctx, fmt.Errorf("error in LNURLPayValues: %s", error_reason)
}
// todo: doesn't work with lnurls from lnbits??
// check whether description hash matches with expected hash
// decode invoice
// bolt11, err := decodepay.Decodepay(response2.PR)
// if err != nil {
// bot.trySendMessage(ctx.Sender(), helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
// errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err.Error())
// log.Errorln(errmsg)
// return ctx, errors.New(errors.InvalidSyntaxError, err)
// }
// if bolt11.DescriptionHash != lnurlPayState.DescriptionHash {
// log.Errorf("[lnurlPayHandlerSend] Error: description hash doesn't match")
// bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "description hash doesn't match.\nExpected: `"+lnurlPayState.DescriptionHash+"` Received: `"+bolt11.DescriptionHash+"`"))
// return ctx, fmt.Errorf("description hash doesn't match")
// }
// all good
lnurlPayState.LNURLPayValues = response2
// add result to persistent struct
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
bot.Telegram.Delete(statusMsg)
m.Text = fmt.Sprintf("/pay %s", response2.PR)
return bot.payHandler(ctx, m)
return bot.payHandler(ctx)
}
func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, address string, amount int64) (context.Context, error) {
func (bot *TipBot) sendToLightningAddress(ctx intercept.Context, address string, amount int64) (intercept.Context, error) {
m := ctx.Message()
split := strings.Split(address, "@")
if len(split) != 2 {
return ctx, fmt.Errorf("lightning address format wrong")
@@ -232,6 +314,5 @@ func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, ad
// this will invoke the "enter amount" dialog in the lnurl handler
m.Text = fmt.Sprintf("/lnurl %s", lnurl)
}
bot.lnurlHandler(ctx, m)
return ctx, nil
return bot.lnurlHandler(ctx)
}
+63 -44
View File
@@ -7,6 +7,9 @@ import (
"io/ioutil"
"net/url"
"github.com/LightningTipBot/LightningTipBot/internal/network"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
@@ -20,11 +23,11 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/str"
lnurl "github.com/fiatjaf/go-lnurl"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
var (
withdrawConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
withdrawConfirmationMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
btnCancelWithdraw = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_withdraw")
btnWithdraw = paymentConfirmationMenu.Data("✅ Withdraw", "confirm_withdraw")
)
@@ -39,38 +42,51 @@ type LnurlWithdrawState struct {
Comment string `json:"comment"`
LanguageCode string `json:"languagecode"`
Success bool `json:"success"`
Invoice lnbits.BitInvoice `json:"invoice"`
Invoice lnbits.Invoice `json:"invoice"`
Message string `json:"message"`
}
type EditSingleButtonParams struct {
Message string
ButtonText string
Data string
URL string
}
// editSingleButton edits a message to display a single button (for something like a progress indicator)
func (bot *TipBot) editSingleButton(ctx context.Context, m *tb.Message, message string, button string) {
bot.tryEditMessage(
func (bot *TipBot) editSingleButton(ctx context.Context, m *tb.Message, params EditSingleButtonParams) (*tb.Message, error) {
if len(params.URL) > 0 && len(params.Data) > 0 {
return &tb.Message{}, fmt.Errorf("URL and Data cannot be set at the same time.")
}
if len(params.URL) == 0 && len(params.Data) == 0 {
params.Data = "placeholder"
}
return bot.tryEditMessage(
m,
message,
params.Message,
&tb.ReplyMarkup{
InlineKeyboard: [][]tb.InlineButton{
{tb.InlineButton{Text: button}},
{tb.InlineButton{Text: params.ButtonText, Data: params.Data, URL: params.URL}},
},
},
)
}
// lnurlWithdrawHandler is invoked when the first lnurl response was a lnurl-withdraw response
// at this point, the user hans't necessarily entered an amount yet
func (bot *TipBot) lnurlWithdrawHandler(ctx context.Context, m *tb.Message, withdrawParams LnurlWithdrawState) {
func (bot *TipBot) lnurlWithdrawHandler(ctx intercept.Context, withdrawParams *LnurlWithdrawState) {
m := ctx.Message()
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
// object that holds all information about the send payment
id := fmt.Sprintf("lnurlw-%d-%s", m.Sender.ID, RandStringRunes(5))
LnurlWithdrawState := LnurlWithdrawState{
Base: storage.New(storage.ID(id)),
From: user,
LNURLWithdrawResponse: withdrawParams.LNURLWithdrawResponse,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
withdrawParams.Base = storage.New(storage.ID(id))
withdrawParams.From = user
withdrawParams.LanguageCode = ctx.Value("publicLanguageCode").(string)
// first we check whether an amount is present in the command
amount, amount_err := decodeAmountFromCommand(m.Text)
@@ -78,36 +94,36 @@ func (bot *TipBot) lnurlWithdrawHandler(ctx context.Context, m *tb.Message, with
// 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
(int64(amount) > (withdrawParams.LNURLWithdrawResponse.MaxWithdrawable/1000) || int64(amount) < (withdrawParams.LNURLWithdrawResponse.MinWithdrawable/1000)) &&
(withdrawParams.LNURLWithdrawResponse.MaxWithdrawable != 0 && withdrawParams.LNURLWithdrawResponse.MinWithdrawable != 0) { // only if max and min are set
err := fmt.Errorf("amount not in range")
log.Warnf("[lnurlWithdrawHandler] Error: %s", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable/1000, LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable/1000))
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), withdrawParams.LNURLWithdrawResponse.MinWithdrawable/1000, withdrawParams.LNURLWithdrawResponse.MaxWithdrawable/1000))
ResetUserState(user, bot)
return
}
// if no amount is entered, and if only one amount is possible, we use it
if amount_err != nil && LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable == LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable {
amount = int64(LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable / 1000)
if amount_err != nil && withdrawParams.LNURLWithdrawResponse.MaxWithdrawable == withdrawParams.LNURLWithdrawResponse.MinWithdrawable {
amount = int64(withdrawParams.LNURLWithdrawResponse.MaxWithdrawable / 1000)
amount_err = nil
}
// set also amount in the state of the user
LnurlWithdrawState.Amount = amount * 1000 // save as mSat
withdrawParams.Amount = amount * 1000 // save as mSat
// add result to persistent struct
runtime.IgnoreError(LnurlWithdrawState.Set(LnurlWithdrawState, bot.Bunt))
runtime.IgnoreError(withdrawParams.Set(withdrawParams, bot.Bunt))
// now we actualy check whether the amount was in the command and if not, ask for it
if amount_err != nil || amount < 1 {
// // no amount was entered, set user state and ask for amount
bot.askForAmount(ctx, id, "LnurlWithdrawState", LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable, LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable, m.Text)
bot.askForAmount(ctx, id, "LnurlWithdrawState", withdrawParams.LNURLWithdrawResponse.MinWithdrawable, withdrawParams.LNURLWithdrawResponse.MaxWithdrawable, m.Text)
return
}
// We need to save the pay state in the user state so we can load the payment in the next handler
paramsJson, err := json.Marshal(LnurlWithdrawState)
// We need to save the pay state in the user state so we can load the payment in the next ctx
paramsJson, err := json.Marshal(withdrawParams)
if err != nil {
log.Errorf("[lnurlWithdrawHandler] Error: %s", err.Error())
// bot.trySendMessage(m.Sender, err.Error())
@@ -115,12 +131,13 @@ func (bot *TipBot) lnurlWithdrawHandler(ctx context.Context, m *tb.Message, with
}
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
// directly go to confirm
bot.lnurlWithdrawHandlerWithdraw(ctx, m)
bot.lnurlWithdrawHandlerWithdraw(ctx)
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) (context.Context, error) {
func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
@@ -188,7 +205,8 @@ func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Messa
}
// confirmPayHandler when user clicked pay on payment confirmation
func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
@@ -212,15 +230,15 @@ func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) (
}
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)
bot.tryEditMessage(c, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
bot.tryDeleteMessage(c)
return ctx, errors.Create(errors.NotActiveError)
}
defer lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt)
user := LoadUser(ctx)
if user.Wallet == nil {
bot.tryDeleteMessage(c.Message)
bot.tryDeleteMessage(c)
return ctx, errors.Create(errors.UserNoWalletError)
}
@@ -228,13 +246,13 @@ func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) (
ResetUserState(user, bot)
// update button text
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlPreparingWithdraw"))
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlPreparingWithdraw")})
callbackUrl, err := url.Parse(lnurlWithdrawState.LNURLWithdrawResponse.Callback)
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
// bot.trySendMessage(c.Sender, Translate(handler.Ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
return ctx, err
}
@@ -250,7 +268,7 @@ func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) (
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"))
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
return ctx, err
}
lnurlWithdrawState.Invoice = invoice
@@ -262,25 +280,25 @@ func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) (
callbackUrl.RawQuery = qs.Encode()
// lnurlWithdrawState loaded
client, err := bot.GetHttpClient()
client, err := network.GetClient(network.ClientTypeClearNet)
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"))
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
return ctx, err
}
res, err := client.Get(callbackUrl.String())
if err != nil || res.StatusCode >= 300 {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Failed.")
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
// bot.trySendMessage(c.Sender, Translate(handler.Ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
return ctx, errors.New(errors.UnknownError, err)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
// bot.trySendMessage(c.Sender, Translate(handler.Ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage")})
return ctx, err
}
@@ -289,12 +307,12 @@ func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) (
json.Unmarshal(body, &response2)
if response2.Status == "OK" {
// update button text
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawSuccess"))
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawSuccess")})
} else {
log.Errorf("[lnurlWithdrawHandlerWithdraw] LNURLWithdraw failed.")
// update button text
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawFailed"))
bot.editSingleButton(ctx, c.Message, EditSingleButtonParams{Message: lnurlWithdrawState.Message, ButtonText: i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawFailed")})
return ctx, errors.New(errors.UnknownError, fmt.Errorf("LNURLWithdraw failed"))
}
@@ -305,7 +323,8 @@ func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) (
}
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
func (bot *TipBot) cancelWithdrawHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
func (bot *TipBot) cancelWithdrawHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
// reset state immediately
user := LoadUser(ctx)
ResetUserState(user, bot)
@@ -328,6 +347,6 @@ func (bot *TipBot) cancelWithdrawHandler(ctx context.Context, c *tb.Callback) (c
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
return ctx, errors.Create(errors.UnknownError)
}
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawCancelled"), &tb.ReplyMarkup{})
bot.tryEditMessage(c, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawCancelled"), &tb.ReplyMarkup{})
return ctx, lnurlWithdrawState.Inactivate(lnurlWithdrawState, bot.Bunt)
}
+107 -37
View File
@@ -2,13 +2,16 @@ package telegram
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/network"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal"
@@ -18,42 +21,38 @@ import (
lnurl "github.com/fiatjaf/go-lnurl"
log "github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
func (bot *TipBot) GetHttpClient() (*http.Client, error) {
client := http.Client{}
if internal.Configuration.Bot.HttpProxy != "" {
proxyUrl, err := url.Parse(internal.Configuration.Bot.HttpProxy)
if err != nil {
log.Errorln(err)
return nil, err
}
client.Transport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)}
}
return &client, nil
}
func (bot TipBot) cancelLnUrlHandler(c *tb.Callback) {
func (bot *TipBot) cancelLnUrlHandler(c *tb.Callback) {
}
// lnurlHandler is invoked on /lnurl command
func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error) {
// commands:
// /lnurl
// /lnurl <LNURL>
// or /lnurl <amount> <LNURL>
m := ctx.Message()
if m.Chat.Type != tb.ChatPrivate {
return ctx, errors.Create(errors.NoPrivateChatError)
}
log.Infof("[lnurlHandler] %s", m.Text)
user := LoadUser(ctx)
log.WithFields(log.Fields{
"module": "lnurl",
"func": "lnurlHandler",
"path": "/lnurl",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"telegram_id": user.Telegram.ID}).Infof("%s", m.Text)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
// if only /lnurl is entered, show the lnurl of the user
if m.Text == "/lnurl" {
return bot.lnurlReceiveHandler(ctx, m)
return bot.lnurlReceiveHandler(ctx)
}
statusMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "lnurlResolvingUrlMessage"))
@@ -68,57 +67,100 @@ func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) (context.Con
lnurlSplit = split[1]
} else {
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "Could not parse command."))
log.Warnln("[/lnurl] Could not parse command.")
log.WithFields(log.Fields{
"module": "lnurl",
"func": "lnurlHandler",
"path": "/lnurl",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"telegram_id": user.Telegram.ID}).Warnln("Could not parse command.")
return ctx, errors.Create(errors.InvalidSyntaxError)
}
// get rid of the URI prefix
lnurlSplit = strings.TrimPrefix(lnurlSplit, "lightning:")
log.Debugf("[lnurlHandler] lnurlSplit: %s", lnurlSplit)
// log.Debugf("[lnurlHandler] lnurlSplit: %s", lnurlSplit)
// HandleLNURL by fiatjaf/go-lnurl
_, params, err := bot.HandleLNURL(lnurlSplit)
if err != nil {
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "LNURL error."))
// bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
log.Warnf("[HandleLNURL] Error: %s", err.Error())
log.WithFields(log.Fields{
"module": "lnurl",
"func": "lnurlHandler",
"path": "/lnurl",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"telegram_id": user.Telegram.ID}).Error(err.Error())
return ctx, err
}
switch params.(type) {
case lnurl.LNURLAuthParams:
authParams := &LnurlAuthState{LNURLAuthParams: params.(lnurl.LNURLAuthParams)}
log.Infof("[LNURL-auth] %s", authParams.LNURLAuthParams.Callback)
log.WithFields(log.Fields{
"module": "lnurl-auth",
"func": "lnurlHandler",
"path": "/lnurl",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"telegram_id": user.Telegram.ID}).Info(authParams.LNURLAuthParams.Callback)
bot.tryDeleteMessage(statusMsg)
return bot.lnurlAuthHandler(ctx, m, *authParams)
ctx.Context, err = bot.lnurlAuthHandler(ctx, m, authParams)
return ctx, err
case lnurl.LNURLPayParams:
payParams := &LnurlPayState{LNURLPayParams: params.(lnurl.LNURLPayParams)}
log.Infof("[LNURL-p] %s", payParams.LNURLPayParams.Callback)
log.WithFields(log.Fields{
"module": "lnurl-p",
"func": "lnurlHandler",
"path": "/lnurl",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"telegram_id": user.Telegram.ID}).Infof(payParams.LNURLPayParams.Callback)
bot.tryDeleteMessage(statusMsg)
// display the metadata image from the first LNURL-p response
if len(payParams.LNURLPayParams.Metadata.Image.Bytes) > 0 {
bot.trySendMessage(m.Sender, &tb.Photo{
File: tb.File{FileReader: bytes.NewReader(payParams.LNURLPayParams.Metadata.Image.Bytes)},
Caption: fmt.Sprintf("%s", payParams.LNURLPayParams.Metadata.Description)})
Caption: payParams.LNURLPayParams.Metadata.Description})
} else if len(payParams.LNURLPayParams.Metadata.Description) > 0 {
// display the metadata text from the first LNURL-p response
// if there was no photo in the last step
bot.trySendMessage(m.Sender, fmt.Sprintf("`%s`", payParams.LNURLPayParams.Metadata.Description))
}
// ask whether to make payment
bot.lnurlPayHandler(ctx, m, *payParams)
bot.lnurlPayHandler(ctx, payParams)
case lnurl.LNURLWithdrawResponse:
withdrawParams := LnurlWithdrawState{LNURLWithdrawResponse: params.(lnurl.LNURLWithdrawResponse)}
log.Infof("[LNURL-w] %s", withdrawParams.LNURLWithdrawResponse.Callback)
withdrawParams := &LnurlWithdrawState{LNURLWithdrawResponse: params.(lnurl.LNURLWithdrawResponse)}
log.WithFields(log.Fields{
"module": "lnurl-w",
"func": "lnurlHandler",
"path": "/lnurl",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"telegram_id": user.Telegram.ID}).Info(withdrawParams.LNURLWithdrawResponse.Callback)
bot.tryDeleteMessage(statusMsg)
bot.lnurlWithdrawHandler(ctx, m, withdrawParams)
bot.lnurlWithdrawHandler(ctx, withdrawParams)
default:
if err == nil {
err = fmt.Errorf("invalid LNURL type")
}
log.Warnln(err)
log.WithFields(log.Fields{
"module": "lnurl",
"func": "lnurlHandler",
"path": "/lnurl",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"telegram_id": user.Telegram.ID}).Warnln(err)
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
// bot.trySendMessage(m.Sender, err.Error())
return ctx, err
@@ -142,7 +184,6 @@ func (bot *TipBot) UserGetAnonLightningAddress(user *lnbits.User) (string, error
func UserGetLNURL(user *lnbits.User) (string, error) {
name := fmt.Sprint(user.UUID)
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, name)
log.Debugf("[lnurlReceiveHandler] %s's LNURL: %s", GetUserStr(user.Telegram), callback)
lnurlEncode, err := lnurl.LNURLEncode(callback)
if err != nil {
@@ -151,8 +192,18 @@ func UserGetLNURL(user *lnbits.User) (string, error) {
return lnurlEncode, nil
}
func UserGetAnonLNURL(user *lnbits.User) (string, error) {
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, user.AnonIDSha256)
lnurlEncode, err := lnurl.LNURLEncode(callback)
if err != nil {
return "", err
}
return lnurlEncode, nil
}
// lnurlReceiveHandler outputs the LNURL of the user
func (bot TipBot) lnurlReceiveHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
func (bot *TipBot) lnurlReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
fromUser := LoadUser(ctx)
lnurlEncode, err := UserGetLNURL(fromUser)
if err != nil {
@@ -176,7 +227,7 @@ func (bot TipBot) lnurlReceiveHandler(ctx context.Context, m *tb.Message) (conte
}
// fiatjaf/go-lnurl 1.8.4 with proxy
func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
var err error
var rawurl string
@@ -211,8 +262,13 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
if err != nil {
return "", nil, err
}
// rerun LNURLDecode to convert lnurlp/keyauth schemes to https://
rawurl, err = lnurl.LNURLDecode(rawurl)
if err != nil {
return "", nil, err
}
}
log.Debug("[HandleLNURL] rawurl: ", rawurl)
parsed, err := url.Parse(rawurl)
if err != nil {
return rawurl, nil, err
@@ -236,7 +292,7 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
// return rawurl, nil, err
// }
client, err := bot.GetHttpClient()
client, err := network.GetClient(network.ClientTypeClearNet)
if err != nil {
return "", nil, err
}
@@ -273,6 +329,20 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
// value, err := lnurl.HandleChannel(b)
// return rawurl, value, err
default:
return rawurl, nil, fmt.Errorf("Unkown LNURL response.")
return rawurl, nil, fmt.Errorf("unkown LNURL response")
}
}
// DescriptionHash is the SHA256 hash of the metadata
func (bot *TipBot) DescriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
var hashString string
var hash [32]byte
if len(payerData) == 0 {
hash = sha256.Sum256([]byte(metadata.Encode()))
hashString = hex.EncodeToString(hash[:])
} else {
hash = sha256.Sum256([]byte(metadata.Encode() + payerData))
hashString = hex.EncodeToString(hash[:])
}
return hashString, nil
}
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"strconv"
"time"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
type Message struct {
+64 -44
View File
@@ -5,6 +5,8 @@ import (
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
@@ -17,11 +19,11 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/str"
decodepay "github.com/fiatjaf/ln-decodepay"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
var (
paymentConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
paymentConfirmationMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
btnCancelPay = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_pay")
btnPay = paymentConfirmationMenu.Data("✅ Pay", "confirm_pay")
)
@@ -48,23 +50,23 @@ type PayData struct {
}
// payHandler invoked on "/pay lnbc..." command
func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
func (bot *TipBot) payHandler(ctx intercept.Context) (intercept.Context, error) {
// check and print all commands
bot.anyTextHandler(ctx, m)
bot.anyTextHandler(ctx)
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
if len(strings.Split(m.Text, " ")) < 2 {
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, ""))
if len(strings.Split(ctx.Message().Text, " ")) < 2 {
NewMessage(ctx.Message(), WithDuration(0, bot))
bot.trySendMessage(ctx.Sender(), helpPayInvoiceUsage(ctx, ""))
return ctx, errors.Create(errors.InvalidSyntaxError)
}
userStr := GetUserStr(m.Sender)
paymentRequest, err := getArgumentFromCommand(m.Text, 1)
userStr := GetUserStr(ctx.Sender())
paymentRequest, err := getArgumentFromCommand(ctx.Message().Text, 1)
if err != nil {
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
NewMessage(ctx.Message(), WithDuration(0, bot))
bot.trySendMessage(ctx.Sender(), helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
errmsg := fmt.Sprintf("[/pay] Error: Could not getArgumentFromCommand: %s", err.Error())
log.Errorln(errmsg)
return ctx, errors.New(errors.InvalidSyntaxError, err)
@@ -76,7 +78,7 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) (context.Conte
// decode invoice
bolt11, err := decodepay.Decodepay(paymentRequest)
if err != nil {
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
bot.trySendMessage(ctx.Sender(), helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err.Error())
log.Errorln(errmsg)
return ctx, errors.New(errors.InvalidSyntaxError, err)
@@ -84,7 +86,7 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) (context.Conte
amount := int64(bolt11.MSatoshi / 1000)
if amount <= 0 {
bot.trySendMessage(m.Sender, Translate(ctx, "invoiceNoAmountMessage"))
bot.trySendMessage(ctx.Sender(), Translate(ctx, "invoiceNoAmountMessage"))
errmsg := fmt.Sprint("[/pay] Error: invoice without amount")
log.Warnln(errmsg)
return ctx, errors.Create(errors.InvalidAmountError)
@@ -93,21 +95,21 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) (context.Conte
// check user balance first
balance, err := bot.GetUserBalance(user)
if err != nil {
NewMessage(m, WithDuration(0, bot))
NewMessage(ctx.Message(), 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"))
bot.trySendMessage(ctx.Sender(), Translate(ctx, "errorTryLaterMessage"))
return ctx, errors.New(errors.GetBalanceError, err)
}
if amount > balance {
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "insufficientFundsMessage"), balance, amount))
NewMessage(ctx.Message(), WithDuration(0, bot))
bot.trySendMessage(ctx.Sender(), fmt.Sprintf(Translate(ctx, "insufficientFundsMessage"), balance, amount))
return ctx, errors.Create(errors.InvalidSyntaxError)
}
// send warning that the invoice might fail due to missing fee reserve
if float64(amount) > float64(balance)*0.99 {
bot.trySendMessage(m.Sender, Translate(ctx, "feeReserveMessage"))
if float64(amount) > float64(balance)*0.98 {
bot.trySendMessage(ctx.Sender(), Translate(ctx, "feeReserveMessage"))
}
confirmText := fmt.Sprintf(Translate(ctx, "confirmPayInvoiceMessage"), amount)
@@ -118,7 +120,7 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) (context.Conte
log.Infof("[/pay] Invoice entered. User: %s, amount: %d sat.", userStr, amount)
// object that holds all information about the send payment
id := fmt.Sprintf("pay-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
id := fmt.Sprintf("pay:%d-%d-%s", ctx.Sender().ID, amount, RandStringRunes(5))
// // // create inline buttons
payButton := paymentConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "confirm_pay", id)
@@ -129,7 +131,7 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) (context.Conte
payButton,
cancelButton),
)
payMessage := bot.trySendMessageEditable(m.Chat, confirmText, paymentConfirmationMenu)
payMessage := bot.trySendMessageEditable(ctx.Chat(), confirmText, paymentConfirmationMenu)
payData := &PayData{
Base: storage.New(storage.ID(id)),
From: user,
@@ -148,8 +150,8 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) (context.Conte
}
// confirmPayHandler when user clicked pay on payment confirmation
func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
tx := &PayData{Base: storage.New(storage.ID(c.Data))}
func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context, error) {
tx := &PayData{Base: storage.New(storage.ID(ctx.Data()))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.Bunt)
@@ -161,23 +163,23 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) (conte
payData := sn.(*PayData)
// onnly the correct user can press
if payData.From.Telegram.ID != c.Sender.ID {
if payData.From.Telegram.ID != ctx.Sender().ID {
return ctx, errors.Create(errors.UnknownError)
}
if !payData.Active {
log.Errorf("[confirmPayHandler] send not active anymore")
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
bot.tryDeleteMessage(c.Message)
bot.tryEditMessage(ctx.Message(), i18n.Translate(payData.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
bot.tryDeleteMessage(ctx.Message())
return ctx, errors.Create(errors.NotActiveError)
}
defer payData.Set(payData, bot.Bunt)
// remove buttons from confirmation message
// bot.tryEditMessage(c.Message, MarkdownEscape(payData.Message), &tb.ReplyMarkup{})
// bot.tryEditMessage(handler.Message(), MarkdownEscape(payData.Message), &tb.ReplyMarkup{})
user := LoadUser(ctx)
if user.Wallet == nil {
bot.tryDeleteMessage(c.Message)
bot.tryDeleteMessage(ctx.Message())
return ctx, errors.Create(errors.UserNoWalletError)
}
@@ -186,26 +188,35 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) (conte
// reset state immediately
ResetUserState(user, bot)
userStr := GetUserStr(c.Sender)
userStr := GetUserStr(ctx.Sender())
// update button text
bot.tryEditMessage(
c.Message,
ctx.Message(),
payData.Message,
&tb.ReplyMarkup{
InlineKeyboard: [][]tb.InlineButton{
{tb.InlineButton{Text: i18n.Translate(payData.LanguageCode, "lnurlGettingUserMessage")}},
{tb.InlineButton{Unique: "attempt_payment", Text: i18n.Translate(payData.LanguageCode, "lnurlGettingUserMessage")}},
},
},
)
log.Infof("[/pay] Attempting %s's invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
log.WithFields(log.Fields{
"module": "telegram",
"func": "confirmPayHandler",
"user": userStr,
"user_id": user.ID,
"telegram_id": user.Telegram.ID,
"path": "/pay",
"data": payData.ID,
"amount": payData.Amount,
"wallet_id": user.Wallet.ID}).Infof("Attempting invoice payment")
// pay invoice
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoiceString}, bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of %s: %s", userStr, err)
err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
bot.tryEditMessage(ctx.Message(), fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
// verbose error message, turned off for now
// if len(err.Error()) == 0 {
// err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
@@ -223,27 +234,36 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) (conte
log.Errorln(errmsg)
}
if c.Message.Private() {
if ctx.Message().Private() {
// if the command was invoked in private chat
// the edit below was cool, but we need to pop up the keyboard again
// bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
bot.tryDeleteMessage(c.Message)
bot.trySendMessage(c.Sender, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
bot.tryDeleteMessage(ctx.Message())
bot.trySendMessage(ctx.Sender(), i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
} else {
// if the command was invoked in group chat
bot.trySendMessage(c.Sender, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePublicPaidMessage"), userStr), &tb.ReplyMarkup{})
bot.trySendMessage(ctx.Sender(), i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
bot.tryEditMessage(ctx.Message(), fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePublicPaidMessage"), userStr), &tb.ReplyMarkup{})
}
log.Infof("[⚡️ pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
log.WithFields(log.Fields{
"module": "telegram",
"func": "confirmPayHandler",
"user": userStr,
"user_id": user.ID,
"telegram_id": user.Telegram.ID,
"path": "⚡️ pay",
"data": payData.ID,
"amount": payData.Amount,
"wallet_id": user.Wallet.ID}).Infof("User paid invoice")
return ctx, nil
}
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
func (bot *TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
func (bot *TipBot) cancelPaymentHandler(ctx intercept.Context) (intercept.Context, error) {
// reset state immediately
user := LoadUser(ctx)
ResetUserState(user, bot)
tx := &PayData{Base: storage.New(storage.ID(c.Data))}
tx := &PayData{Base: storage.New(storage.ID(ctx.Data()))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
// immediatelly set intransaction to block duplicate calls
@@ -254,12 +274,12 @@ func (bot *TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) (co
}
payData := sn.(*PayData)
// onnly the correct user can press
if payData.From.Telegram.ID != c.Sender.ID {
if payData.From.Telegram.ID != ctx.Callback().Sender.ID {
return ctx, errors.Create(errors.UnknownError)
}
// delete and send instead of edit for the keyboard to pop up after sending
bot.tryDeleteMessage(c.Message)
bot.trySendMessage(c.Message.Chat, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"))
bot.tryDeleteMessage(ctx.Message())
bot.trySendMessage(ctx.Message().Chat, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"))
// bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"), &tb.ReplyMarkup{})
return ctx, payData.Inactivate(payData, bot.Bunt)
+13 -11
View File
@@ -2,13 +2,14 @@ package telegram
import (
"bytes"
"context"
"encoding/json"
"fmt"
"image"
"image/jpeg"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
@@ -17,10 +18,10 @@ import (
"github.com/nfnt/resize"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// TryRecognizeInvoiceFromQrCode will try to read an invoice string from a qr code and invoke the payment handler.
// TryRecognizeInvoiceFromQrCode will try to read an invoice string from a qr code and invoke the payment ctx.
func TryRecognizeQrCode(img image.Image) (*gozxing.Result, error) {
// check for qr code
bmp, _ := gozxing.NewBinaryBitmapFromImage(img)
@@ -33,14 +34,15 @@ func TryRecognizeQrCode(img image.Image) (*gozxing.Result, error) {
payload := strings.ToLower(result.String())
if lightning.IsInvoice(payload) || lightning.IsLnurl(payload) {
// create payment command payload
// invoke payment confirmation handler
// invoke payment confirmation ctx
return result, nil
}
return nil, fmt.Errorf("no codes found")
}
// photoHandler is the handler function for every photo from a private chat that the bot receives
func (bot *TipBot) photoHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
func (bot *TipBot) photoHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
if m.Chat.Type != tb.ChatPrivate {
return ctx, errors.Create(errors.NoPrivateChatError)
}
@@ -49,13 +51,13 @@ func (bot *TipBot) photoHandler(ctx context.Context, m *tb.Message) (context.Con
}
user := LoadUser(ctx)
if c := stateCallbackMessage[user.StateKey]; c != nil {
ctx, err := c(ctx, m)
ctx, err := c(ctx)
ResetUserState(user, bot)
return ctx, err
}
// get file reader closer from Telegram api
reader, err := bot.Telegram.GetFile(m.Photo.MediaFile())
reader, err := bot.Telegram.File(m.Photo.MediaFile())
if err != nil {
log.Errorf("[photoHandler] getfile error: %v\n", err.Error())
return ctx, err
@@ -77,10 +79,10 @@ func (bot *TipBot) photoHandler(ctx context.Context, m *tb.Message) (context.Con
// invoke payment handler
if lightning.IsInvoice(data.String()) {
m.Text = fmt.Sprintf("/pay %s", data.String())
return bot.payHandler(ctx, m)
return bot.payHandler(ctx)
} else if lightning.IsLnurl(data.String()) {
m.Text = fmt.Sprintf("/lnurl %s", data.String())
return bot.lnurlHandler(ctx, m)
return bot.lnurlHandler(ctx)
}
return ctx, nil
}
@@ -94,11 +96,11 @@ func DownloadProfilePicture(telegram *tb.Bot, user *tb.User) ([]byte, error) {
return nil, err
}
if len(photo) == 0 {
log.Debugln("[DownloadProfilePicture] No profile picture found")
log.Error("[DownloadProfilePicture] No profile picture found")
return nil, err
}
buf := new(bytes.Buffer)
reader, err := telegram.GetFile(&photo[0].File)
reader, err := telegram.File(&photo[0].File)
if err != nil {
log.Errorf("[DownloadProfilePicture] %v", err)
return nil, err
+723
View File
@@ -0,0 +1,723 @@
package telegram
import (
"bytes"
"context"
"encoding/base64"
"encoding/hex"
"encoding/pem"
"fmt"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
tb "gopkg.in/lightningtipbot/telebot.v3"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/satdress"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/eko/gocache/store"
log "github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode"
)
var (
registerNodeMessage = "📖 Connect your Lightning node with your wallet.\n\nCurrently supported backends: `lnd` and `lnbits`\nTo register a node, type: `/node add <type> <info>`\n\n*LND (REST):* `/node add lnd <host> <macaroon> <cert>`\n*LNbits:* `/node add lnbits <host> <key>`\n\nℹ️ Always use `https://` for the `<host>`, even if you use a Tor node. Certificates and macaroons need to be in base64 format.\n\n⚠️ For security reasons, you should *only use an invoice macaroon* for LND and an *invoice key* for LNbits."
nodeHelpMessage = "⚙️ *Commands:*\n`/node add <type> <info>` ✅ Add your node.\n`/node invoice <admount>` ⤵️ Fetch an invoice from your node.\n`/node proxy <amount>` 🔀 Proxy a payment to your node (privacy feature).\n`/node help` 📖 Show help."
checkingInvoiceMessage = "⏳ Checking invoice on your node..."
invoiceNotSettledMessage = "❌ Invoice has not settled yet."
checkInvoiceButtonMessage = "🔄 Check invoice"
routingInvoiceMessage = "🔄 Getting invoice from your node..."
checkingNodeMessage = "🔄 Checking your node..."
errorCouldNotAddNodeMessage = "❌ Could not add node. Please check your node details."
gettingInvoiceOnlyErrorMessage = "❌ Error getting invoice from your node."
gettingInvoiceErrorMessage = "❌ Error getting invoice from your node. Your funds are still available."
payingInvoiceErrorMessage = "❌ Could not route payment. Your funds are still available."
invoiceRoutedMessage = "✅ *Payment routed to your node.*"
invoiceSettledMessage = "✅ *Invoice settled.*"
nodeAddedMessage = "✅ *Node added.*"
satdressCheckInvoicenMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
btnSatdressCheckInvoice = satdressCheckInvoicenMenu.Data(checkInvoiceButtonMessage, "satdress_check_invoice")
)
// todo -- rename to something better like parse node settings or something
func parseUserSettingInput(ctx intercept.Context, m *tb.Message) (satdress.BackendParams, error) {
// input is "/node add <Type> <Host> <Macaroon> <Cert>"
params := satdress.LNDParams{}
splits := strings.Split(m.Text, " ")
splitlen := len(splits)
if splitlen < 4 {
return params, fmt.Errorf("not enough arguments")
}
switch strings.ToLower(splits[2]) {
case "lnd":
if splitlen < 5 || splitlen > 7 {
return params, fmt.Errorf("wrong format. Use <Type> <Host> <Macaroon> [<Cert>]")
}
host := splits[3]
macaroon := splits[4]
var pem []byte
if splitlen == 6 {
cert := splits[5]
pem := parseCertificateToPem(cert)
if len(pem) < 1 {
return params, fmt.Errorf("certificate has invalid format")
}
}
hostsplit := strings.Split(host, ".")
if len(hostsplit) == 0 {
return params, fmt.Errorf("host has wrong format")
}
return satdress.LNDParams{
Cert: pem,
Host: host,
Macaroon: macaroon,
CertString: string(pem),
}, nil
case "lnbits":
if splitlen < 5 || splitlen > 6 {
return params, fmt.Errorf("wrong format. Use <Type> <Host> <Key>")
}
host := splits[3]
key := splits[4]
host = strings.TrimSuffix(host, "/")
hostsplit := strings.Split(host, ".")
if len(hostsplit) == 0 {
return params, fmt.Errorf("host has wrong format")
}
return satdress.LNBitsParams{
Host: host,
Key: key,
}, nil
default:
return params, fmt.Errorf("unknown backend type. Supported types: `lnd`, `lnbits`")
}
}
func nodeInfoString(node *lnbits.NodeSettings) (string, error) {
if len(node.NodeType) == 0 {
return "", fmt.Errorf("node type is empty")
}
var node_info_str_filled string
var node_info_str string
switch strings.ToLower(node.NodeType) {
case "lnd":
node_info_str = "*Type:* `%s`\n\n*Host:*\n\n`%s`\n\n*Macaroon:*\n\n`%s`\n\n*Cert:*\n\n`%s`"
node_info_str_filled = fmt.Sprintf(node_info_str, node.NodeType, node.LNDParams.Host, node.LNDParams.Macaroon, node.LNDParams.CertString)
case "lnbits":
node_info_str = "*Type:* `%s`\n\n*Host:*\n\n`%s`\n\n*Key:*\n\n`%s`"
node_info_str_filled = fmt.Sprintf(node_info_str, node.NodeType, node.LNbitsParams.Host, node.LNbitsParams.Key)
default:
return "", fmt.Errorf("unknown node type")
}
return fmt.Sprintf("ℹ️ *Your node information.*\n\n%s", node_info_str_filled), nil
}
func (bot *TipBot) nodeHelpHandler(ctx intercept.Context) (intercept.Context, error) {
bot.trySendMessage(ctx.Message().Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
return ctx, nil
}
func (bot *TipBot) getNodeHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
if err != nil {
log.WithFields(log.Fields{
"module": "telegram",
"func": "getNodeHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID}).Infof("Could not get user settings for user")
return ctx, err
}
if user.Settings == nil {
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
return ctx, fmt.Errorf("no node registered")
}
node_info_str, err := nodeInfoString(&user.Settings.Node)
if err != nil {
log.WithFields(log.Fields{
"module": "telegram",
"func": "getNodeHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID}).Infof("Could not get node info for user")
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
return ctx, err
}
bot.trySendMessage(m.Sender, node_info_str)
return ctx, nil
}
func (bot *TipBot) nodeHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
splits := strings.Split(m.Text, " ")
if len(splits) == 1 {
return bot.getNodeHandler(ctx)
} else if len(splits) > 1 {
switch strings.ToLower(splits[1]) {
case "invoice":
return bot.invHandler(ctx)
case "add":
return bot.registerNodeHandler(ctx)
case "check":
return bot.satdressCheckInvoiceHandler(ctx)
case "proxy":
return bot.satdressProxyHandler(ctx)
case "help":
return bot.nodeHelpHandler(ctx)
}
}
return ctx, nil
}
func (bot *TipBot) registerNodeHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
if err != nil {
return ctx, err
}
check_message := bot.trySendMessageEditable(user.Telegram, checkingNodeMessage)
backendParams, err := parseUserSettingInput(ctx, m)
if err != nil {
bot.tryEditMessage(check_message, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
return ctx, err
}
switch backend := backendParams.(type) {
case satdress.LNDParams:
// get test invoice from user's node
getInvoiceParams, err := satdress.MakeInvoice(
satdress.Params{
Backend: backend,
Msatoshi: 1000,
Description: "Test invoice",
},
)
if err != nil {
log.WithFields(log.Fields{
"module": "telegram",
"func": "registerNodeHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"backend": user.Settings.Node.NodeType,
"error": err.Error(),
"status": getInvoiceParams.Status}).Errorf("Could not add user %s's %s node: %s", user.GetUserStr(), getInvoiceParams.Status, err.Error())
bot.tryEditMessage(check_message, errorCouldNotAddNodeMessage)
return ctx, err
}
// save node in db
user.Settings.Node.LNDParams = &backend
user.Settings.Node.NodeType = "lnd"
case satdress.LNBitsParams:
// get test invoice from user's node
getInvoiceParams, err := satdress.MakeInvoice(
satdress.Params{
Backend: backend,
Msatoshi: 1000,
Description: "Test invoice",
},
)
if err != nil {
log.Errorf("[registerNodeHandler] Could not add user %s's %s node: %s", user.GetUserStr(), getInvoiceParams.Status, err.Error())
bot.tryEditMessage(check_message, errorCouldNotAddNodeMessage)
return ctx, err
}
// save node in db
user.Settings.Node.LNbitsParams = &backend
user.Settings.Node.NodeType = "lnbits"
}
err = UpdateUserRecord(user, *bot)
if err != nil {
log.Errorf("[registerNodeHandler] could not update record of user %s: %v", user.GetUserStr(), err)
return ctx, err
}
node_info_str, err := nodeInfoString(&user.Settings.Node)
if err != nil {
log.WithFields(log.Fields{
"module": "telegram",
"func": "registerNodeHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID}).Infof("Could not get node info for user")
bot.trySendMessage(m.Sender, registerNodeMessage+"\n\n"+nodeHelpMessage)
return ctx, err
}
bot.tryEditMessage(check_message, fmt.Sprintf("%s\n\n%s", node_info_str, nodeAddedMessage))
log.WithFields(log.Fields{
"module": "telegram",
"func": "registerNodeHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"backend": user.Settings.Node.NodeType}).Infof("Added node")
return ctx, nil
}
func (bot *TipBot) invHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
if err != nil {
return ctx, err
}
if user.Settings == nil || user.Settings.Node.NodeType == "" {
bot.trySendMessage(m.Sender, "You did not register a node yet.")
return ctx, fmt.Errorf("node of user %s not registered", user.GetUserStr())
}
var amount int64
if amount_str, err := getArgumentFromCommand(m.Text, 2); err == nil {
amount, err = GetAmount(amount_str)
if err != nil {
return ctx, err
}
}
log.WithFields(log.Fields{
"module": "satdress",
"func": "invHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID}).Infof("Getting invoice with backend %s", user.Settings.Node.NodeType)
check_message := bot.trySendMessageEditable(user.Telegram, routingInvoiceMessage)
var getInvoiceParams satdress.CheckInvoiceParams
switch user.Settings.Node.NodeType {
case "lnd":
// get invoice from user's node
getInvoiceParams, err = satdress.MakeInvoice(
satdress.Params{
Backend: satdress.LNDParams{
Cert: []byte(user.Settings.Node.LNDParams.CertString),
Host: user.Settings.Node.LNDParams.Host,
Macaroon: user.Settings.Node.LNDParams.Macaroon,
},
Msatoshi: amount * 1000,
Description: fmt.Sprintf("Invoice by %s", GetUserStr(bot.Telegram.Me)),
},
)
case "lnbits":
// get invoice from user's node
getInvoiceParams, err = satdress.MakeInvoice(
satdress.Params{
Backend: satdress.LNBitsParams{
Key: user.Settings.Node.LNbitsParams.Key,
Host: user.Settings.Node.LNbitsParams.Host,
},
Msatoshi: amount * 1000,
Description: fmt.Sprintf("Invoice by %s", GetUserStr(bot.Telegram.Me)),
},
)
default:
return ctx, fmt.Errorf("unknown node type %s", user.Settings.Node.NodeType)
}
if err != nil {
log.Errorln(err.Error())
bot.tryEditMessage(check_message, gettingInvoiceOnlyErrorMessage)
return ctx, err
}
// bot.trySendMessage(m.Sender, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
// create qr code
qr, err := qrcode.Encode(getInvoiceParams.PR, qrcode.Medium, 256)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
log.Errorln(errmsg)
return ctx, err
}
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", getInvoiceParams.PR)})
// add the getInvoiceParams to cache to check it later
bot.Cache.Set(fmt.Sprintf("invoice:%d", user.Telegram.ID), getInvoiceParams, &store.Options{Expiration: 24 * time.Hour})
log.WithFields(log.Fields{
"module": "satdress",
"func": "invHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID}).Infof("Invoice created with backend %s", user.Settings.Node.NodeType)
// check if invoice settles
return bot.satdressCheckInvoiceHandler(ctx)
}
func (bot *TipBot) satdressCheckInvoiceHandler(ctx intercept.Context) (intercept.Context, error) {
tgUser := LoadUser(ctx).Telegram
user, err := GetLnbitsUserWithSettings(tgUser, *bot)
if err != nil {
return ctx, err
}
// get the getInvoiceParams from cache
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressCheckInvoiceHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"key": fmt.Sprintf("invoice:%d", user.Telegram.ID)},
).Debugf("Getting key")
getInvoiceParamsInterface, err := bot.Cache.Get(fmt.Sprintf("invoice:%d", user.Telegram.ID))
if err != nil {
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressCheckInvoiceHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"key": fmt.Sprintf("invoice:%d", user.Telegram.ID)},
).Errorf(err.Error())
return ctx, err
}
getInvoiceParams := getInvoiceParamsInterface.(satdress.CheckInvoiceParams)
// check the invoice
// check if there is an invoice check message in cache already
check_message_interface, err := bot.Cache.Get(fmt.Sprintf("invoice:msg:%s", getInvoiceParams.Hash))
var check_message *tb.Message
if err != nil {
// send a new message if there isn't one in the cache
check_message = bot.trySendMessageEditable(tgUser, checkingInvoiceMessage)
} else {
check_message = check_message_interface.(*tb.Message)
check_message, err = bot.tryEditMessage(check_message, checkingInvoiceMessage)
if err != nil {
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressCheckInvoiceHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"key": fmt.Sprintf("invoice:%d", user.Telegram.ID)},
).Errorf(err.Error())
}
}
// save it in the cache for another call later
bot.Cache.Set(fmt.Sprintf("invoice:msg:%s", getInvoiceParams.Hash), check_message, &store.Options{Expiration: 24 * time.Hour})
deadLineCtx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Second*60))
runtime.NewRetryTicker(deadLineCtx, "node_invoice_check", runtime.WithRetryDuration(5*time.Second)).Do(func() {
// get invoice from user's node
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressCheckInvoiceHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"key": fmt.Sprintf("invoice:%d", user.Telegram.ID),
"invoice": getInvoiceParams.Hash},
).Debugf("Checking invoice")
getInvoiceParams, err = satdress.CheckInvoice(getInvoiceParams)
if err != nil {
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressCheckInvoiceHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"key": fmt.Sprintf("invoice:%d", user.Telegram.ID)},
).Errorln(err.Error())
return
}
if getInvoiceParams.Status == "SETTLED" {
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressCheckInvoiceHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"key": fmt.Sprintf("invoice:%d", user.Telegram.ID),
"invoice": getInvoiceParams.Hash},
).Debugf("Invoice settled")
bot.tryEditMessage(check_message, invoiceSettledMessage)
cancel()
}
}, func() {
// cancel
},
func() {
// deadline
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressCheckInvoiceHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"key": fmt.Sprintf("invoice:%d", user.Telegram.ID),
"invoice": getInvoiceParams.Hash},
).Debugf("Invoice check expired")
bot.tryEditMessage(check_message, invoiceNotSettledMessage,
&tb.ReplyMarkup{
InlineKeyboard: [][]tb.InlineButton{
{tb.InlineButton{Text: checkInvoiceButtonMessage, Unique: "satdress_check_invoice"}},
},
})
},
)
return ctx, nil
}
func parseCertificateToPem(cert string) []byte {
block, _ := pem.Decode([]byte(cert))
if block != nil {
// already PEM
return []byte(cert)
} else {
var dec []byte
dec, err := hex.DecodeString(cert)
if err != nil {
// not HEX
dec, err = base64.StdEncoding.DecodeString(cert)
if err != nil {
// not base54, we have a problem huston
return nil
}
}
if block, _ := pem.Decode(dec); block != nil {
return dec
}
// decoding went wrong
return nil
}
}
func (bot *TipBot) satdressProxyHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
if err != nil {
return ctx, err
}
if user.Settings == nil || user.Settings.Node.LNDParams == nil {
bot.trySendMessage(user.Telegram, "You did not register a node yet.")
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressProxyHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID},
).Errorf("node of user %s not registered", user.GetUserStr())
return ctx, fmt.Errorf("no node settings")
}
var amount int64
if amount_str, err := getArgumentFromCommand(m.Text, 2); err == nil {
amount, err = GetAmount(amount_str)
if err != nil {
return ctx, err
}
}
memo := "🔀 Payment proxy in."
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, InvoiceCallbackSatdressProxy, "")
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressProxyHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID},
).Errorln(errmsg)
return ctx, err
}
// create qr code
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
bot.trySendMessage(user.Telegram, Translate(ctx, "errorTryLaterMessage"))
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressProxyHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"backend": user.Settings.Node.NodeType},
).Errorln(errmsg)
return ctx, err
}
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressProxyHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"backend": user.Settings.Node.NodeType},
).Infof("Proxy payment done")
return ctx, nil
}
func (bot *TipBot) satdressProxyRelayPaymentHandler(event Event) {
invoiceEvent := event.(*InvoiceEvent)
user := invoiceEvent.User
if user.Settings == nil || user.Settings.Node.LNDParams == nil {
bot.trySendMessage(user.Telegram, "You did not register a node yet.")
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressProxyRelayPaymentHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID},
).Errorf("node not registered")
return
}
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressProxyRelayPaymentHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"backend": user.Settings.Node.NodeType},
).Infof("Relaying payment", user.GetUserStr(), user.Settings.Node.NodeType)
bot.notifyInvoiceReceivedEvent(invoiceEvent)
// now relay the payment to the user's node
var amount int64 = invoiceEvent.Amount
check_message := bot.trySendMessageEditable(user.Telegram, routingInvoiceMessage)
var getInvoiceParams satdress.CheckInvoiceParams
var err error
if user.Settings.Node.NodeType == "lnd" {
// get invoice from user's node
getInvoiceParams, err = satdress.MakeInvoice(
satdress.Params{
Backend: satdress.LNDParams{
Cert: []byte(user.Settings.Node.LNDParams.CertString),
Host: user.Settings.Node.LNDParams.Host,
Macaroon: user.Settings.Node.LNDParams.Macaroon,
},
Msatoshi: amount * 1000,
Description: fmt.Sprintf("🔀 Payment proxy out from %s.", GetUserStr(bot.Telegram.Me)),
},
)
} else if user.Settings.Node.NodeType == "lnbits" {
// get invoice from user's node
getInvoiceParams, err = satdress.MakeInvoice(
satdress.Params{
Backend: satdress.LNBitsParams{
Key: user.Settings.Node.LNbitsParams.Key,
Host: user.Settings.Node.LNbitsParams.Host,
},
Msatoshi: amount * 1000,
Description: fmt.Sprintf("🔀 Payment proxy out from %s.", GetUserStr(bot.Telegram.Me)),
},
)
}
if err != nil {
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressProxyRelayPaymentHandler",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"backend": user.Settings.Node.NodeType},
).Errorln(err.Error())
bot.tryEditMessage(check_message, gettingInvoiceErrorMessage)
return
}
// bot.trySendMessage(user.Telegram, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressProxyRelayPaymentHandler",
"user": GetUserStr(user.Telegram),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"backend": user.Settings.Node.NodeType},
).Infof("Retrieved invoice for payment. Paying...")
// pay invoice
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: getInvoiceParams.PR}, bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of %s: %s", GetUserStr(user.Telegram), err)
// err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
// verbose error message, turned off for now
// if len(err.Error()) == 0 {
// err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
// }
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), str.MarkdownEscape(err.Error())), &tb.ReplyMarkup{})
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressProxyRelayPaymentHandler",
"user": GetUserStr(user.Telegram),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"backend": user.Settings.Node.NodeType},
).Errorln(errmsg)
bot.tryEditMessage(check_message, payingInvoiceErrorMessage)
return
}
// object that holds all information about the send payment
id := fmt.Sprintf("proxypay:%d:%d:%s", user.Telegram.ID, amount, RandStringRunes(8))
payData := &PayData{
Base: storage.New(storage.ID(id)),
From: user,
Invoice: invoice.PaymentRequest,
Hash: invoice.PaymentHash,
Amount: amount,
}
// add result to persistent struct
runtime.IgnoreError(payData.Set(payData, bot.Bunt))
// add the getInvoiceParams to cache to check it later
bot.Cache.Set(fmt.Sprintf("invoice:%d", user.Telegram.ID), getInvoiceParams, &store.Options{Expiration: 24 * time.Hour})
time.Sleep(time.Second)
getInvoiceParams, err = satdress.CheckInvoice(getInvoiceParams)
if err != nil {
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressProxyRelayPaymentHandler",
"user": GetUserStr(user.Telegram),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"backend": user.Settings.Node.NodeType,
"invoice": invoice.PaymentRequest},
).Errorln(err.Error())
return
}
bot.tryEditMessage(check_message, invoiceRoutedMessage)
log.WithFields(log.Fields{
"module": "satdress",
"func": "satdressProxyRelayPaymentHandler",
"user": GetUserStr(user.Telegram),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"backend": user.Settings.Node.NodeType,
"invoice": invoice.PaymentRequest},
).Infof("Proxy paid invoice")
// bot.trySendMessage(user.Telegram, fmt.Sprintf("PR: `%s`\n\nHash: `%s`\n\nStatus: `%s`", getInvoiceParams.PR, string(getInvoiceParams.Hash), getInvoiceParams.Status))
return
}
+105 -64
View File
@@ -4,8 +4,12 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/log"
"github.com/sirupsen/logrus"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
@@ -17,12 +21,11 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
var (
sendConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
sendConfirmationMenu = &tb.ReplyMarkup{ResizeKeyboard: true}
btnCancelSend = sendConfirmationMenu.Data("🚫 Cancel", "cancel_send")
btnSend = sendConfirmationMenu.Data("✅ Send", "confirm_send")
)
@@ -55,8 +58,9 @@ type SendData struct {
}
// sendHandler invoked on "/send 123 @user" command
func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
bot.anyTextHandler(ctx, m)
func (bot *TipBot) sendHandler(ctx intercept.Context) (intercept.Context, error) {
bot.anyTextHandler(ctx)
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
@@ -68,8 +72,8 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Cont
// check and print all commands
// If the send is a reply, then trigger /tip handler
if m.IsReply() && m.Chat.Type != tb.ChatPrivate {
return bot.tipHandler(ctx, m)
if ctx.Message().IsReply() && ctx.Message().Chat.Type != tb.ChatPrivate {
return bot.tipHandler(ctx)
}
@@ -80,23 +84,28 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Cont
// }
// get send amount, returns 0 if no amount is given
amount, err := decodeAmountFromCommand(m.Text)
amount, err := decodeAmountFromCommand(ctx.Text())
// info: /send 10 <user> DEMANDS an amount, while /send <ln@address.com> also works without
// todo: /send <user> should also invoke amount input dialog if no amount is given
// CHECK whether first or second argument is a LIGHTNING ADDRESS
arg := ""
if len(strings.Split(m.Text, " ")) > 2 {
arg, err = getArgumentFromCommand(m.Text, 2)
} else if len(strings.Split(m.Text, " ")) == 2 {
arg, err = getArgumentFromCommand(m.Text, 1)
logFields := logrus.Fields{
"module": "telegram",
"func": "sendHandler",
"path": "/send",
}
if len(strings.Split(ctx.Message().Text, " ")) > 2 {
arg, err = getArgumentFromCommand(ctx.Message().Text, 2)
} else if len(strings.Split(ctx.Message().Text, " ")) == 2 {
arg, err = getArgumentFromCommand(ctx.Message().Text, 1)
}
if err == nil {
if lightning.IsLightningAddress(arg) {
// lightning address, send to that address
ctx, err = bot.sendToLightningAddress(ctx, m, arg, amount)
ctx, err = bot.sendToLightningAddress(ctx, arg, amount)
if err != nil {
log.Errorln(err.Error())
log.WithObjects(ctx, user, err).WithFields(logFields).Errorln(err.Error())
return ctx, err
}
return ctx, err
@@ -104,68 +113,68 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Cont
}
// is a user given?
arg, err = getArgumentFromCommand(m.Text, 1)
if err != nil && m.Chat.Type == tb.ChatPrivate {
_, err = bot.askForUser(ctx, "", "CreateSendState", m.Text)
arg, err = getArgumentFromCommand(ctx.Message().Text, 1)
if err != nil && ctx.Message().Chat.Type == tb.ChatPrivate {
_, err = bot.askForUser(ctx, "", "CreateSendState", ctx.Message().Text)
return ctx, err
}
// is an amount given?
amount, err = decodeAmountFromCommand(m.Text)
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
_, err = bot.askForAmount(ctx, "", "CreateSendState", 0, 0, m.Text)
amount, err = decodeAmountFromCommand(ctx.Message().Text)
if (err != nil || amount < 1) && ctx.Message().Chat.Type == tb.ChatPrivate {
_, err = bot.askForAmount(ctx, "", "CreateSendState", 0, 0, ctx.Message().Text)
return ctx, err
}
// ASSUME INTERNAL SEND TO TELEGRAM USER
if err != nil || amount < 1 {
errmsg := fmt.Sprintf("[/send] Error: Send amount not valid.")
log.Warnln(errmsg)
log.WithObjects(ctx, user, err).WithFields(logFields).Warnln(errmsg)
// immediately delete if the amount is bullshit
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, helpSendUsage(ctx, Translate(ctx, "sendValidAmountMessage")))
NewMessage(ctx.Message(), WithDuration(0, bot))
bot.trySendMessage(ctx.Sender(), helpSendUsage(ctx, Translate(ctx, "sendValidAmountMessage")))
return ctx, err
}
// SEND COMMAND IS VALID
// check for memo in command
sendMemo := GetMemoFromCommand(m.Text, 3)
sendMemo := GetMemoFromCommand(ctx.Message().Text, 3)
toUserStrMention := ""
toUserStrWithoutAt := ""
// check for user in command, accepts user mention or plain username without @
if len(m.Entities) > 1 && m.Entities[1].Type == "mention" {
toUserStrMention = m.Text[m.Entities[1].Offset : m.Entities[1].Offset+m.Entities[1].Length]
if len(ctx.Message().Entities) > 1 && ctx.Message().Entities[1].Type == "mention" {
toUserStrMention = ctx.Message().Text[ctx.Message().Entities[1].Offset : ctx.Message().Entities[1].Offset+ctx.Message().Entities[1].Length]
toUserStrWithoutAt = strings.TrimPrefix(toUserStrMention, "@")
} else {
toUserStrWithoutAt, err = getArgumentFromCommand(m.Text, 2)
toUserStrWithoutAt, err = getArgumentFromCommand(ctx.Message().Text, 2)
if err != nil {
log.Errorln(err.Error())
log.WithObjects(ctx, user, err).WithFields(logFields).Errorln(err.Error())
return ctx, err
}
toUserStrWithoutAt = strings.TrimPrefix(toUserStrWithoutAt, "@")
toUserStrMention = "@" + toUserStrWithoutAt
}
err = bot.parseCmdDonHandler(ctx, m)
err = bot.parseDonationCommandHandler(ctx)
if err == nil {
return ctx, errors.Create(errors.InvalidSyntaxError)
}
toUserDb, err := GetUserByTelegramUsername(toUserStrWithoutAt, *bot)
if err != nil {
NewMessage(m, WithDuration(0, bot))
NewMessage(ctx.Message(), 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)))
bot.trySendMessage(ctx.Message().Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), str.MarkdownEscape(toUserStrMention)))
return ctx, err
}
if user.ID == toUserDb.ID {
bot.trySendMessage(m.Sender, Translate(ctx, "sendYourselfMessage"))
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "sendYourselfMessage"))
return ctx, errors.Create(errors.SelfPaymentError)
}
@@ -175,7 +184,7 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Cont
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmSendAppendMemo"), str.MarkdownEscape(sendMemo))
}
// object that holds all information about the send payment
id := fmt.Sprintf("send-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
id := fmt.Sprintf("send-%d-%d-%s", ctx.Message().Sender.ID, amount, RandStringRunes(5))
sendData := &SendData{
From: user,
Base: storage.New(storage.ID(id)),
@@ -191,9 +200,9 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Cont
sendDataJson, err := json.Marshal(sendData)
if err != nil {
NewMessage(m, WithDuration(0, bot))
log.Printf("[/send] Error: %s\n", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprint(Translate(ctx, "errorTryLaterMessage")))
NewMessage(ctx.Message(), WithDuration(0, bot))
log.WithObjects(ctx, user, err).WithFields(logFields).Error("error marshaling sendData")
bot.trySendMessage(ctx.Message().Sender, fmt.Sprint(Translate(ctx, "errorTryLaterMessage")))
return ctx, err
}
// save the send data to the Database
@@ -209,10 +218,10 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Cont
sendButton,
cancelButton),
)
if m.Private() {
bot.trySendMessage(m.Chat, confirmText, sendConfirmationMenu)
if ctx.Message().Private() {
bot.trySendMessage(ctx.Chat(), confirmText, sendConfirmationMenu)
} else {
bot.tryReplyMessage(m, confirmText, sendConfirmationMenu)
bot.tryReplyMessage(ctx.Message(), confirmText, sendConfirmationMenu)
}
return ctx, nil
}
@@ -221,7 +230,8 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Cont
// it will pop up a new keyboard with the last interacted contacts to send funds to
// then, the flow is handled as if the user entered /send (then ask for contacts from keyboard or entry,
// then ask for an amount).
func (bot *TipBot) keyboardSendHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
func (bot *TipBot) keyboardSendHandler(ctx intercept.Context) (intercept.Context, error) {
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
@@ -231,10 +241,15 @@ func (bot *TipBot) keyboardSendHandler(ctx context.Context, m *tb.Message) (cont
Type: "CreateSendState",
OiringalCommand: "/send",
}
logFields := logrus.Fields{
"module": "telegram",
"func": "keyboardSendHandler",
"path": "/send",
}
// set LNURLPayParams in the state of the user
stateDataJson, err := json.Marshal(enterUserStateData)
if err != nil {
log.Errorln(err)
log.WithObjects(ctx, user, err).WithFields(logFields).Errorln(err)
return ctx, err
}
SetUserState(user, bot, lnbits.UserEnterUser, string(stateDataJson))
@@ -243,8 +258,8 @@ func (bot *TipBot) keyboardSendHandler(ctx context.Context, m *tb.Message) (cont
// if no contact is found (one entry will always be inside, it's the enter user button)
// immediatelly go to the send handler
if len(sendToButtons) == 1 {
m.Text = "/send"
return bot.sendHandler(ctx, m)
ctx.Message().Text = "/send"
return bot.sendHandler(ctx)
}
// Attention! We need to ues the original Telegram.Send command here!
@@ -252,28 +267,39 @@ func (bot *TipBot) keyboardSendHandler(ctx context.Context, m *tb.Message) (cont
// this is suboptimal because Telegram.Send is not rate limited etc. but it's the only way to send a custom keyboard for now
_, err = bot.Telegram.Send(user.Telegram, Translate(ctx, "enterUserMessage"), sendToMenu)
if err != nil {
log.Errorln(err.Error())
log.WithObjects(ctx, user, err).WithFields(logFields).Errorln(err.Error())
}
return ctx, nil
}
// sendHandler invoked when user clicked send on payment confirmation
func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
tx := &SendData{Base: storage.New(storage.ID(c.Data))}
func (bot *TipBot) confirmSendHandler(ctx intercept.Context) (intercept.Context, error) {
tx := &SendData{Base: storage.New(storage.ID(ctx.Data()))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
logFields := logrus.Fields{
"module": "telegram",
"func": "confirmSendHandler",
"path": "button",
}
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[acceptSendHandler] %s", err.Error())
log.WithObjects(ctx, tx.From).WithFields(logFields).WithFields(logrus.Fields{
"to_telegram_id": tx.ToTelegramId,
"to_user": tx.ToTelegramUser},
).Errorf("could not find transaction")
return ctx, err
}
sendData := sn.(*SendData)
// onnly the correct user can press
if sendData.From.Telegram.ID != c.Sender.ID {
if sendData.From.Telegram.ID != ctx.Callback().Sender.ID {
return ctx, errors.Create(errors.UnknownError)
}
if !sendData.Active {
log.Errorf("[acceptSendHandler] send not active anymore")
log.WithObjects(ctx, tx.From).WithFields(logFields).WithFields(logrus.Fields{
"to_user": sendData.ToTelegramUser,
"to_telegram_id": sendData.ToTelegramId},
).Errorf("send not active anymore")
// bot.tryDeleteMessage(c.Message)
return ctx, errors.Create(errors.NotActiveError)
}
@@ -292,12 +318,15 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) (cont
toUserStrWithoutAt := sendData.ToTelegramUser
amount := sendData.Amount
sendMemo := sendData.Memo
// we can now get the wallets of both users
to, err := GetLnbitsUser(&tb.User{ID: toId, Username: toUserStrWithoutAt}, *bot)
if err != nil {
log.Errorln(err.Error())
bot.tryDeleteMessage(c.Message)
log.WithObjects(ctx, from, err).WithFields(logFields).WithFields(logrus.Fields{
"to_user_id": to.ID,
"to_user": sendData.ToTelegramUser,
"to_telegram_id": sendData.ToTelegramId},
).Errorln("erro fetching lnbits user")
bot.tryDeleteMessage(ctx.Callback().Message)
return ctx, err
}
toUserStrMd := GetUserStrMd(to.Telegram)
@@ -305,7 +334,7 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) (cont
toUserStr := GetUserStr(to.Telegram)
fromUserStr := GetUserStr(from.Telegram)
transactionMemo := fmt.Sprintf("Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
transactionMemo := fmt.Sprintf("💸 Send from %s to %s.", fromUserStr, toUserStr)
t := NewTransaction(bot, from, to, amount, TransactionType("send"))
t.Memo = transactionMemo
@@ -313,27 +342,35 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) (cont
if !success || err != nil {
// bot.trySendMessage(c.Sender, sendErrorMessage)
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err.Error())
log.Errorln(errmsg)
bot.tryEditMessage(c.Message, i18n.Translate(sendData.LanguageCode, "sendErrorMessage"), &tb.ReplyMarkup{})
log.WithObjects(ctx, from, err).WithFields(logrus.Fields{
"to_user": toUserStr,
"to_user_id": to.ID,
"to_telegram_id": to.Telegram.ID},
).Errorln(errmsg)
bot.tryEditMessage(ctx.Callback().Message, i18n.Translate(sendData.LanguageCode, "sendErrorMessage"), &tb.ReplyMarkup{})
return ctx, errors.Create(errors.UnknownError)
}
sendData.Inactivate(sendData, bot.Bunt)
log.Infof("[💸 send] Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
log.WithObjects(ctx, from, err).WithFields(logrus.Fields{
"to_user": toUserStr,
"to_user_id": to.ID,
"to_telegram_id": to.Telegram.ID,
"amount": amount}).Infof("Send confirmation received")
// notify to user
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
// bot.trySendMessage(from.Telegram, fmt.Sprintf(Translate(ctx, "sendSentMessage"), amount, toUserStrMd))
if c.Message.Private() {
if ctx.Callback().Message.Private() {
// if the command was invoked in private chat
// the edit below was cool, but we need to get rid of the replymarkup inline keyboard thingy for the main menu to pop up
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd), &tb.ReplyMarkup{})
bot.tryDeleteMessage(c.Message)
bot.trySendMessage(c.Sender, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
bot.tryDeleteMessage(ctx.Callback().Message)
bot.trySendMessage(ctx.Callback().Sender, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
} else {
// if the command was invoked in group chat
bot.trySendMessage(c.Sender, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendPublicSentMessage"), amount, fromUserStrMd, toUserStrMd), &tb.ReplyMarkup{})
bot.trySendMessage(ctx.Callback().Sender, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
bot.tryEditMessage(ctx.Callback().Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendPublicSentMessage"), amount, fromUserStrMd, toUserStrMd), &tb.ReplyMarkup{})
}
// send memo if it was present
if len(sendMemo) > 0 {
@@ -344,8 +381,9 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) (cont
}
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
func (bot *TipBot) cancelSendHandler(ctx intercept.Context) (intercept.Context, error) {
// reset state immediately
c := ctx.Callback()
user := LoadUser(ctx)
ResetUserState(user, bot)
tx := &SendData{Base: storage.New(storage.ID(c.Data))}
@@ -353,7 +391,10 @@ func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) (conte
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[acceptSendHandler] %s", err.Error())
log.WithObjects(ctx, user, err).WithFields(logrus.Fields{
"module": "telegram",
"func": "cancelSendHandler"},
).Errorf(err.Error())
return ctx, err
}
@@ -363,7 +404,7 @@ func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) (conte
return ctx, errors.Create(errors.UnknownError)
}
// delete and send instead of edit for the keyboard to pop up after sending
bot.tryDeleteMessage(c.Message)
bot.tryDeleteMessage(c)
bot.trySendMessage(c.Message.Chat, i18n.Translate(sendData.LanguageCode, "sendCancelledMessage"))
sendData.Inactivate(sendData, bot.Bunt)
return ctx, nil
+216 -144
View File
@@ -4,9 +4,13 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/log"
"github.com/sirupsen/logrus"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
@@ -15,8 +19,7 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/eko/gocache/store"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
type ShopView struct {
@@ -26,7 +29,6 @@ type ShopView struct {
Page int
Message *tb.Message
StatusMessages []*tb.Message
Chat *tb.Chat
}
type ShopItem struct {
@@ -81,7 +83,7 @@ func (shop *Shop) getItem(itemId string) (item ShopItem, ok bool) {
}
var (
shopKeyboard = &tb.ReplyMarkup{ResizeReplyKeyboard: false}
shopKeyboard = &tb.ReplyMarkup{ResizeKeyboard: false}
browseShopButton = shopKeyboard.Data("Browse shops", "shops_browse")
shopNewShopButton = shopKeyboard.Data("New Shop", "shops_newshop")
shopDeleteShopButton = shopKeyboard.Data("Delete Shops", "shops_deleteshop")
@@ -114,8 +116,9 @@ var (
)
// shopItemPriceHandler is invoked when the user presses the item settings button to set a price
func (bot *TipBot) shopItemPriceHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopItemPriceHandler] %s", c.Data)
func (bot *TipBot) shopItemPriceHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
log.WithObjects(ctx).Debugf("[shopItemPriceHandler] %s", c.Data)
user := LoadUser(ctx)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
@@ -128,7 +131,7 @@ func (bot *TipBot) shopItemPriceHandler(ctx context.Context, c *tb.Callback) (co
item := shop.Items[shop.ItemIds[shopView.Page]]
// sanity check
if item.ID != c.Data {
log.Error("[shopItemPriceHandler] item id mismatch")
log.WithObjects(ctx).Error("[shopItemPriceHandler] item id mismatch")
return ctx, errors.Create(errors.ItemIdMismatchError)
}
// We need to save the pay state in the user state so we can load the payment in the next handler
@@ -138,9 +141,10 @@ func (bot *TipBot) shopItemPriceHandler(ctx context.Context, c *tb.Callback) (co
}
// enterShopItemPriceHandler is invoked when the user enters a price amount
func (bot *TipBot) enterShopItemPriceHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
log.Debugf("[enterShopItemPriceHandler] %s", m.Text)
func (bot *TipBot) enterShopItemPriceHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[enterShopItemPriceHandler] %s", m.Text)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
return ctx, err
@@ -155,7 +159,7 @@ func (bot *TipBot) enterShopItemPriceHandler(ctx context.Context, m *tb.Message)
item := shop.Items[shop.ItemIds[shopView.Page]]
// sanity check
if item.ID != user.StateData {
log.Error("[shopItemPriceHandler] item id mismatch")
log.WithObjects(ctx, user).Error("[shopItemPriceHandler] item id mismatch")
return ctx, fmt.Errorf("item id mismatch")
}
@@ -163,18 +167,18 @@ func (bot *TipBot) enterShopItemPriceHandler(ctx context.Context, m *tb.Message)
if m.Text == "0" {
amount = 0
} else {
amount, err = getAmount(m.Text)
amount, err = GetAmount(m.Text)
if err != nil {
log.Warnf("[enterShopItemPriceHandler] %s", err.Error())
log.WithObjects(ctx, user).Warnf("[enterShopItemPriceHandler] %s", err.Error())
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
ResetUserState(user, bot)
return ctx, err
}
}
if amount > 200 {
bot.sendStatusMessageAndDelete(ctx, m.Sender, fmt.Sprintf("ℹ️ During alpha testing, price can be max 200 sat."))
amount = 200
if amount > 2000 {
bot.sendStatusMessageAndDelete(ctx, m.Sender, "ℹ️ During testing, price can be max 2000 sat.")
amount = 2000
}
item.Price = amount
shop.Items[item.ID] = item
@@ -191,9 +195,10 @@ func (bot *TipBot) enterShopItemPriceHandler(ctx context.Context, m *tb.Message)
}
// shopItemPriceHandler is invoked when the user presses the item settings button to set a item title
func (bot *TipBot) shopItemTitleHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopItemTitleHandler] %s", c.Data)
func (bot *TipBot) shopItemTitleHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[shopItemTitleHandler] %s", c.Data)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
return ctx, err
@@ -205,7 +210,7 @@ func (bot *TipBot) shopItemTitleHandler(ctx context.Context, c *tb.Callback) (co
item := shop.Items[shop.ItemIds[shopView.Page]]
// sanity check
if item.ID != c.Data {
log.Error("[shopItemTitleHandler] item id mismatch")
log.WithObjects(ctx, user).Error("[shopItemTitleHandler] item id mismatch")
return ctx, errors.Create(errors.ItemIdMismatchError)
}
// We need to save the pay state in the user state so we can load the payment in the next handler
@@ -215,9 +220,10 @@ func (bot *TipBot) shopItemTitleHandler(ctx context.Context, c *tb.Callback) (co
}
// enterShopItemTitleHandler is invoked when the user enters a title of the item
func (bot *TipBot) enterShopItemTitleHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
log.Debugf("[enterShopItemTitleHandler] %s", m.Text)
func (bot *TipBot) enterShopItemTitleHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[enterShopItemTitleHandler] %s", m.Text)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
return ctx, err
@@ -232,7 +238,7 @@ func (bot *TipBot) enterShopItemTitleHandler(ctx context.Context, m *tb.Message)
item := shop.Items[shop.ItemIds[shopView.Page]]
// sanity check
if item.ID != user.StateData {
log.Error("[enterShopItemTitleHandler] item id mismatch")
log.WithObjects(ctx, user).Error("[enterShopItemTitleHandler] item id mismatch")
return ctx, errors.Create(errors.ItemIdMismatchError)
}
if len(m.Text) == 0 {
@@ -264,9 +270,10 @@ func (bot *TipBot) enterShopItemTitleHandler(ctx context.Context, m *tb.Message)
}
// shopItemSettingsHandler is invoked when the user presses the item settings button
func (bot *TipBot) shopItemSettingsHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopItemSettingsHandler] %s", c.Data)
func (bot *TipBot) shopItemSettingsHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[shopItemSettingsHandler] %s", c.Data)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
return ctx, err
@@ -275,7 +282,7 @@ func (bot *TipBot) shopItemSettingsHandler(ctx context.Context, c *tb.Callback)
item := shop.Items[shop.ItemIds[shopView.Page]]
// sanity check
if item.ID != c.Data {
log.Error("[shopItemSettingsHandler] item id mismatch")
log.WithObjects(ctx, user).Error("[shopItemSettingsHandler] item id mismatch")
return ctx, errors.Create(errors.ItemIdMismatchError)
}
if item.TbPhoto != nil {
@@ -286,9 +293,10 @@ func (bot *TipBot) shopItemSettingsHandler(ctx context.Context, c *tb.Callback)
}
// shopItemPriceHandler is invoked when the user presses the item settings button to set a item title
func (bot *TipBot) shopItemDeleteHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopItemDeleteHandler] %s", c.Data)
func (bot *TipBot) shopItemDeleteHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[shopItemDeleteHandler] %s", c.Data)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
return ctx, err
@@ -335,9 +343,10 @@ func (bot *TipBot) shopItemDeleteHandler(ctx context.Context, c *tb.Callback) (c
}
// displayShopItemHandler is invoked when the user presses the back button in the item settings
func (bot *TipBot) displayShopItemHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[displayShopItemHandler] c.Data: %s", c.Data)
func (bot *TipBot) displayShopItemHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[displayShopItemHandler] c.Data: %s", c.Data)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
return ctx, err
@@ -357,9 +366,10 @@ func (bot *TipBot) displayShopItemHandler(ctx context.Context, c *tb.Callback) (
}
// shopNextItemHandler is invoked when the user presses the next item button
func (bot *TipBot) shopNextItemButtonHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopNextItemButtonHandler] c.Data: %s", c.Data)
func (bot *TipBot) shopNextItemButtonHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[shopNextItemButtonHandler] c.Data: %s", c.Data)
// shopView, err := bot.Cache.Get(fmt.Sprintf("shopview-%d", user.Telegram.ID))
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
@@ -379,16 +389,17 @@ func (bot *TipBot) shopNextItemButtonHandler(ctx context.Context, c *tb.Callback
}
// shopPrevItemButtonHandler is invoked when the user presses the previous item button
func (bot *TipBot) shopPrevItemButtonHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopPrevItemButtonHandler] %s", c.Data)
func (bot *TipBot) shopPrevItemButtonHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[shopPrevItemButtonHandler] %s", c.Data)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
return ctx, err
}
if shopView.Page == 0 {
c.Message.Text = "/shops " + shopView.ShopOwner.Telegram.Username
return bot.shopsHandler(ctx, c.Message)
return bot.shopsHandler(ctx)
}
if shopView.Page > 0 {
@@ -421,12 +432,12 @@ func (bot *TipBot) getItemTitle(ctx context.Context, item *ShopItem) string {
// displayShopItem renders the current item in the shopView
// requires that the shopview page is already set accordingly
// m is the message that will be edited
func (bot *TipBot) displayShopItem(ctx context.Context, m *tb.Message, shop *Shop) *tb.Message {
func (bot *TipBot) displayShopItem(ctx intercept.Context, m *tb.Message, shop *Shop) *tb.Message {
user := LoadUser(ctx)
log.Debugf("[displayShopItem] User: %d shop: %s", GetUserStr(user.Telegram), shop.ID)
logFields := ctx.Context.Value("fields").(logrus.Fields)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
log.Errorf("[displayShopItem] %s", err.Error())
log.WithObjects(ctx, user).WithFields(logFields).Errorf("[displayShopItem] %s", err.Error())
return nil
}
// failsafe: if the page is out of bounds, reset it
@@ -435,8 +446,10 @@ func (bot *TipBot) displayShopItem(ctx context.Context, m *tb.Message, shop *Sho
} else if len(shop.Items) == 0 {
shopView.Page = 0
}
log.Debugf("[displayShopItem] shop: %s page: %d items: %d", shop.ID, shopView.Page, len(shop.Items))
logFields["shop"] = shop.ID
logFields["page"] = shopView.Page
logFields["items"] = len(shop.Items)
log.WithObjects(ctx, user).WithFields(logFields).Debug("displaying shop items")
if len(shop.Items) == 0 {
no_items_message := "There are no items in this shop yet."
if shopView.Message != nil && len(shopView.Message.Text) > 0 {
@@ -445,7 +458,7 @@ func (bot *TipBot) displayShopItem(ctx context.Context, m *tb.Message, shop *Sho
if shopView.Message != nil {
bot.tryDeleteMessage(shopView.Message)
}
shopView.Message = bot.trySendMessage(shopView.Chat, no_items_message, bot.shopMenu(ctx, shop, &ShopItem{}))
shopView.Message = bot.trySendMessage(shopView.Message.Chat, no_items_message, bot.shopMenu(ctx, shop, &ShopItem{}))
}
shopView.Page = 0
return shopView.Message
@@ -487,25 +500,29 @@ func (bot *TipBot) displayShopItem(ctx context.Context, m *tb.Message, shop *Sho
}
// shopHandler is invoked when the user enters /shop
func (bot *TipBot) shopHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
log.Debugf("[shopHandler] %s", m.Text)
func (bot *TipBot) shopHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
if !m.Private() {
return ctx, errors.Create(errors.NoPrivateChatError)
}
user := LoadUser(ctx)
shopOwner := user
logFields := ctx.Context.Value("fields").(logrus.Fields)
logFields["text"] = m.Text
log.WithObjects(ctx, user).WithFields(logFields).Debug("displaying shop items")
// when no argument is given, i.e. command is only /shop, load /shops
shop := &Shop{}
if len(strings.Split(m.Text, " ")) < 2 || !strings.HasPrefix(strings.Split(m.Text, " ")[1], "shop-") {
return bot.shopsHandler(ctx, m)
return bot.shopsHandler(ctx)
} else {
// else: get shop by shop ID
shopID := strings.Split(m.Text, " ")[1]
var err error
shop, err = bot.getShop(ctx, shopID)
if err != nil {
log.Errorf("[shopHandler] %s", err.Error())
log.WithObjects(ctx, user, err).WithFields(logFields).Error("error fetching shop")
return ctx, err
}
}
@@ -515,7 +532,6 @@ func (bot *TipBot) shopHandler(ctx context.Context, m *tb.Message) (context.Cont
ShopID: shop.ID,
Page: 0,
ShopOwner: shopOwner,
Chat: m.Chat,
}
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
shopView.Message = bot.displayShopItem(ctx, m, shop)
@@ -533,12 +549,16 @@ func (bot *TipBot) shopHandler(ctx context.Context, m *tb.Message) (context.Cont
}
// shopNewItemHandler is invoked when the user presses the new item button
func (bot *TipBot) shopNewItemHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopNewItemHandler] %s", c.Data)
func (bot *TipBot) shopNewItemHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
logFields := ctx.Context.Value("fields").(logrus.Fields)
log.WithObjects(ctx, user).WithFields(logFields).Debug("creating new item")
shop, err := bot.getShop(ctx, c.Data)
if err != nil {
log.Errorf("[shopNewItemHandler] %s", err.Error())
log.WithObjects(ctx, user, err).WithFields(logFields).Error("error fetching shop")
return ctx, err
}
if shop.Owner.Telegram.ID != c.Sender.ID {
@@ -552,7 +572,7 @@ func (bot *TipBot) shopNewItemHandler(ctx context.Context, c *tb.Callback) (cont
// 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(shop)
if err != nil {
log.Errorf("[lnurlWithdrawHandler] Error: %s", err.Error())
log.WithObjects(ctx, user, err).WithFields(logFields).Error("error marshaling shop")
// bot.trySendMessage(m.Sender, err.Error())
return ctx, err
}
@@ -562,14 +582,16 @@ func (bot *TipBot) shopNewItemHandler(ctx context.Context, c *tb.Callback) (cont
}
// addShopItem is a helper function for creating a shop item in the database
func (bot *TipBot) addShopItem(ctx context.Context, shopId string) (*Shop, ShopItem, error) {
log.Debugf("[addShopItem] shopId: %s", shopId)
func (bot *TipBot) addShopItem(ctx intercept.Context, shopId string) (*Shop, ShopItem, error) {
user := LoadUser(ctx)
log.WithObjects(ctx, user).WithFields(logrus.Fields{"shop": shopId}).Debug("adding shop item")
shop, err := bot.getShop(ctx, shopId)
if err != nil {
log.Errorf("[addShopItem] %s", err.Error())
log.WithObjects(ctx, user, err).WithFields(logrus.Fields{"shop": shopId}).Error("error fetching shop")
return shop, ShopItem{}, err
}
user := LoadUser(ctx)
// onnly the correct user can press
if shop.Owner.Telegram.ID != user.Telegram.ID {
return shop, ShopItem{}, fmt.Errorf("not owner")
@@ -593,9 +615,11 @@ func (bot *TipBot) addShopItem(ctx context.Context, shopId string) (*Shop, ShopI
}
// addShopItemPhoto is invoked when the users sends a photo as a new item
func (bot *TipBot) addShopItemPhoto(ctx context.Context, m *tb.Message) (context.Context, error) {
log.Debugf("[addShopItemPhoto] <Photo>")
func (bot *TipBot) addShopItemPhoto(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user := LoadUser(ctx)
log.WithObjects(ctx, user).WithFields(logrus.Fields{"func": "addShopItemPhoto", "module": "telegram"}).Debug("adding shop item photo")
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
@@ -604,7 +628,7 @@ func (bot *TipBot) addShopItemPhoto(ctx context.Context, m *tb.Message) (context
var state_shop Shop
err := json.Unmarshal([]byte(user.StateData), &state_shop)
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
log.WithObjects(ctx, user, err).WithFields(logrus.Fields{"func": "addShopItemPhoto", "module": "telegram"}).Errorf("error unmarshaling state")
bot.trySendMessage(m.Sender, Translate(ctx, "errorTryLaterMessage"), Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
@@ -638,27 +662,31 @@ func (bot *TipBot) addShopItemPhoto(ctx context.Context, m *tb.Message) (context
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
bot.displayShopItem(ctx, shopView.Message, shop)
log.Infof("[🛍 shop] %s added an item %s:%s.", GetUserStr(user.Telegram), shop.ID, item.ID)
log.WithObjects(ctx, user).WithFields(logrus.Fields{"func": "addShopItemPhoto", "module": "telegram", "shop": shop.ID, "item": item.ID}).
Infof("[🛍 shop] added new item")
return ctx, nil
}
// ------------------- item files ----------
// shopItemAddItemHandler is invoked when the user presses the new item button
func (bot *TipBot) shopItemAddItemHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopItemAddItemHandler] %s", c.Data)
func (bot *TipBot) shopItemAddItemHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
logFields := ctx.Context.Value("fields").(logrus.Fields)
logFields["data"] = c.Data
log.WithObjects(ctx, user).WithFields(logFields).Debugf("new item")
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
log.Errorf("[shopItemAddItemHandler] %s", err.Error())
log.WithObjects(ctx, user, err).Errorf("error fetching shop view")
return ctx, err
}
shop, err := bot.getShop(ctx, shopView.ShopID)
if err != nil {
log.Errorf("[shopItemAddItemHandler] %s", err.Error())
log.WithObjects(ctx, user, err).Errorf("error fetching shop ")
return ctx, err
}
@@ -676,24 +704,25 @@ func (bot *TipBot) shopItemAddItemHandler(ctx context.Context, c *tb.Callback) (
}
// addItemFileHandler is invoked when the users sends a new file for the item
func (bot *TipBot) addItemFileHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
log.Debugf("[addItemFileHandler] <File>")
func (bot *TipBot) addItemFileHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
log.Errorf("[addItemFileHandler] %s", err.Error())
log.WithObjects(ctx, user, err).Errorf("error fetching shop view")
return ctx, err
}
shop, err := bot.getShop(ctx, shopView.ShopID)
if err != nil {
log.Errorf("[shopNewItemHandler] %s", err.Error())
log.WithObjects(ctx, user, err).Errorf("error fetching shop")
return ctx, err
}
log.WithObjects(ctx, user).WithFields(logrus.Fields{"func": "addItemFileHandler", "module": "telegram", "shop": shop.ID}).Debugf("adding new file")
itemID := user.StateData
item := shop.Items[itemID]
@@ -720,8 +749,9 @@ func (bot *TipBot) addItemFileHandler(ctx context.Context, m *tb.Message) (conte
item.FileIDs = append(item.FileIDs, m.Sticker.FileID)
item.FileTypes = append(item.FileTypes, "sticker")
} else {
log.Errorf("[addItemFileHandler] no file found")
return ctx, errors.Create(errors.NoFileFoundError)
err = errors.Create(errors.NoFileFoundError)
log.WithObjects(ctx, user, err).Errorf("no file found")
return ctx, err
}
shop.Items[item.ID] = item
@@ -765,24 +795,28 @@ func (bot *TipBot) addItemFileHandler(ctx context.Context, m *tb.Message) (conte
// bot.shopViewDeleteAllStatusMsgs(ctx, user)
// }()
bot.displayShopItem(ctx, shopView.Message, shop)
log.Infof("[🛍 shop] %s added a file to shop:item %s:%s.", GetUserStr(user.Telegram), shop.ID, item.ID)
log.WithObjects(ctx, user).WithFields(logrus.Fields{"func": "addItemFileHandler", "module": "telegram", "shop": shop.ID, "item": item.ID}).Infof("[🛍 shop] added file")
return ctx, nil
}
func (bot *TipBot) shopGetItemFilesHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopGetItemFilesHandler] %s", c.Data)
func (bot *TipBot) shopGetItemFilesHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
logFields := ctx.Context.Value("fields").(logrus.Fields)
user := LoadUser(ctx)
logFields["data"] = c.Data
log.WithObjects(ctx, user).WithFields(logFields).Debugf("buy item button clicked")
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
log.Errorf("[addItemFileHandler] %s", err.Error())
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("error fetching shop view")
return ctx, err
}
shop, err := bot.getShop(ctx, shopView.ShopID)
if err != nil {
log.Errorf("[shopGetItemFilesHandler] %s", err.Error())
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("error feching shop")
return ctx, err
}
itemID := c.Data
@@ -803,32 +837,39 @@ func (bot *TipBot) shopGetItemFilesHandler(ctx context.Context, c *tb.Callback)
// for i, fileID := range item.FileIDs {
// bot.sendFileByID(ctx, c.Sender, fileID, item.FileTypes[i])
// }
// log.Infof("[🛍 shop] %s got %d items from %s's item %s (for %d sat).", GetUserStr(user.Telegram), len(item.FileIDs), GetUserStr(shop.Owner.Telegram), item.ID, item.Price)
// log.Infof("[🛍 shop] %s got %d items from %s's item %s (for %d sat).", user.GetUserStr(), len(item.FileIDs), GetUserStr(shop.Owner.Telegram), item.ID, item.Price)
return ctx, nil
}
// shopConfirmBuyHandler is invoked when the user has confirmed to pay for an item
func (bot *TipBot) shopConfirmBuyHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopConfirmBuyHandler] %s", c.Data)
func (bot *TipBot) shopConfirmBuyHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
logFields := ctx.Context.Value("fields").(logrus.Fields)
logFields["data"] = c.Data
log.WithObjects(ctx, user).WithFields(logFields).Debugf("user confirmed to pay item")
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
log.Errorf("[shopConfirmBuyHandler] %s", err.Error())
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("error fetching shop view")
return ctx, err
}
shop, err := bot.getShop(ctx, shopView.ShopID)
if err != nil {
log.Errorf("[shopConfirmBuyHandler] %s", err.Error())
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("error fetching shop")
return ctx, err
}
logFields["shop_title"] = shop.Title
logFields["shop"] = shop.ID
itemID := c.Data
item := shop.Items[itemID]
logFields["item"] = item.ID
if item.Owner.ID != shop.Owner.ID {
log.Errorf("[shopConfirmBuyHandler] Owners do not match.")
return ctx, errors.Create(errors.NotShopOwnerError)
err = errors.Create(errors.NotShopOwnerError)
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("Owners do not match.")
return ctx, err
}
from := user
to := shop.Owner
@@ -838,11 +879,13 @@ func (bot *TipBot) shopConfirmBuyHandler(ctx context.Context, c *tb.Callback) (c
toUserStr := GetUserStr(to.Telegram)
toUserStrMd := GetUserStrMd(to.Telegram)
amount := item.Price
logFields["amount"] = amount
if amount <= 0 {
log.Errorf("[shopConfirmBuyHandler] item has no price.")
return ctx, errors.Create(errors.InvalidAmountError)
err = errors.Create(errors.InvalidAmountError)
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("item has no price")
return ctx, err
}
transactionMemo := fmt.Sprintf("Buy item %s (%d sat).", toUserStr, amount)
transactionMemo := fmt.Sprintf("🛍 Shop from %s.", toUserStr)
t := NewTransaction(bot, from, to, amount, TransactionType("shop"))
t.Memo = transactionMemo
@@ -850,8 +893,8 @@ func (bot *TipBot) shopConfirmBuyHandler(ctx context.Context, c *tb.Callback) (c
if !success || err != nil {
// bot.trySendMessage(c.Sender, sendErrorMessage)
errmsg := fmt.Sprintf("[shop] Error: Transaction failed. %s", err.Error())
log.Errorln(errmsg)
ctx = context.WithValue(ctx, "callback_response", i18n.Translate(user.Telegram.LanguageCode, "sendErrorMessage"))
log.WithObjects(ctx, user, err).WithFields(logFields).Errorln(errmsg)
ctx.Context = context.WithValue(ctx, "callback_response", i18n.Translate(user.Telegram.LanguageCode, "sendErrorMessage"))
// bot.trySendMessage(user.Telegram, i18n.Translate(user.Telegram.LanguageCode, "sendErrorMessage"), &tb.ReplyMarkup{})
return ctx, errors.New(errors.UnknownError, err)
}
@@ -860,29 +903,33 @@ func (bot *TipBot) shopConfirmBuyHandler(ctx context.Context, c *tb.Callback) (c
if len(item.Title) > 0 {
shopItemTitle = fmt.Sprintf("%s", item.Title)
}
ctx = context.WithValue(ctx, "callback_response", "🛍 Purchase successful.")
logFields["item_title"] = shopItemTitle
ctx.Context = context.WithValue(ctx, "callback_response", "🛍 Purchase successful.")
bot.trySendMessage(to.Telegram, fmt.Sprintf("🛍 Someone bought `%s` from your shop `%s` for `%d sat`.", str.MarkdownEscape(shopItemTitle), str.MarkdownEscape(shop.Title), amount))
bot.trySendMessage(from.Telegram, fmt.Sprintf("🛍 You bought `%s` from %s's shop `%s` for `%d sat`.", str.MarkdownEscape(shopItemTitle), toUserStrMd, str.MarkdownEscape(shop.Title), amount))
log.Infof("[🛍 shop] %s bought from %s shop: %s item: %s for %d sat.", toUserStr, GetUserStr(to.Telegram), shop.Title, shopItemTitle, amount)
logFields["to_user"] = GetUserStr(to.Telegram)
log.WithObjects(ctx, user, err).WithFields(logFields).Infof("[🛍 shop] sold item")
bot.shopSendItemFilesToUser(ctx, user, itemID)
return ctx, nil
}
// shopSendItemFilesToUser is a handler function to send itemID's files to the user
func (bot *TipBot) shopSendItemFilesToUser(ctx context.Context, toUser *lnbits.User, itemID string) {
log.Debugf("[shopSendItemFilesToUser] %s -> %s", GetUserStr(toUser.Telegram), itemID)
func (bot *TipBot) shopSendItemFilesToUser(ctx intercept.Context, toUser *lnbits.User, itemID string) {
user := LoadUser(ctx)
logFields := logrus.Fields{"to_user": GetUserStr(toUser.Telegram), "item": itemID}
log.WithObjects(ctx, user).WithFields(logFields).Debugf("sending files to user")
if user.Wallet == nil {
return // errors.New("user has no wallet"), 0
}
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
log.Errorf("[shopGetItemFilesHandler] %s", err.Error())
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("[shopGetItemFilesHandler] %s", err.Error())
return
}
shop, err := bot.getShop(ctx, shopView.ShopID)
if err != nil {
log.Errorf("[addItemFileHandler] %s", err.Error())
log.WithObjects(ctx, user, err).WithFields(logFields).Errorf("[addItemFileHandler] %s", err.Error())
return
}
item := shop.Items[itemID]
@@ -892,7 +939,11 @@ func (bot *TipBot) shopSendItemFilesToUser(ctx context.Context, toUser *lnbits.U
for i, fileID := range item.FileIDs {
bot.sendFileByID(ctx, toUser.Telegram, fileID, item.FileTypes[i])
}
log.Infof("[🛍 shop] %s got %d items from %s's item %s (for %d sat).", GetUserStr(user.Telegram), len(item.FileIDs), GetUserStr(shop.Owner.Telegram), item.ID, item.Price)
logFields["amount"] = len(item.FileIDs)
logFields["from_user"] = GetUserStr(shop.Owner.Telegram)
logFields["item"] = item.ID
logFields["price"] = item.Price
log.WithObjects(ctx, user).WithFields(logFields).Infof("[🛍 shop] files sent to user")
// delete old shop and show again below the files
if shopView.Message != nil {
@@ -939,17 +990,18 @@ var ShopsTextHelp = "⚠️ Shops are still in beta. Expect bugs."
var ShopsNoShopsText = "*There are no shops here yet.*"
// shopsHandlerCallback is a warpper for shopsHandler for callbacks
func (bot *TipBot) shopsHandlerCallback(ctx context.Context, c *tb.Callback) (context.Context, error) {
return bot.shopsHandler(ctx, c.Message)
func (bot *TipBot) shopsHandlerCallback(ctx intercept.Context) (intercept.Context, error) {
return bot.shopsHandler(ctx)
}
// shopsHandler is invoked when the user enters /shops
func (bot *TipBot) shopsHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
log.Debugf("[shopsHandler] %s", GetUserStr(m.Sender))
func (bot *TipBot) shopsHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
if !m.Private() {
return ctx, errors.Create(errors.NoPrivateChatError)
}
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("invoked shops hanler")
shopOwner := user
// if the user in the command, i.e. /shops @user
@@ -965,7 +1017,7 @@ func (bot *TipBot) shopsHandler(ctx context.Context, m *tb.Message) (context.Con
var err error
toUserStrWithoutAt, err = getArgumentFromCommand(m.Text, 1)
if err != nil {
log.Errorln(err.Error())
log.WithObjects(ctx, user, err).Errorln("error reading args from command")
return ctx, err
}
toUserStrWithoutAt = strings.TrimPrefix(toUserStrWithoutAt, "@")
@@ -993,14 +1045,15 @@ func (bot *TipBot) shopsHandler(ctx context.Context, m *tb.Message) (context.Con
}
if shopOwner == nil {
log.Error("[shopsHandler] shopOwner is nil")
return ctx, errors.Create(errors.ShopNoOwnerError)
err := errors.Create(errors.ShopNoOwnerError)
log.WithObjects(ctx, user, err).Error("[shopsHandler] shopOwner is nil")
return ctx, err
}
shops, err := bot.getUserShops(ctx, shopOwner)
if err != nil && user.Telegram.ID == shopOwner.Telegram.ID {
shops, err = bot.initUserShops(ctx, user)
if err != nil {
log.Errorf("[shopsHandler] %s", err.Error())
log.WithObjects(ctx, user, err).Errorf("failed initializing user shops")
return ctx, err
}
}
@@ -1015,7 +1068,7 @@ func (bot *TipBot) shopsHandler(ctx context.Context, m *tb.Message) (context.Con
for _, shopId := range shops.Shops {
shop, err := bot.getShop(ctx, shopId)
if err != nil {
log.Errorf("[shopsHandler] %s", err.Error())
log.WithObjects(ctx, user, err).Errorf("error fetching shop")
return ctx, err
}
shopTitles += fmt.Sprintf("\n· %s (%d items)", str.MarkdownEscape(shop.Title), len(shop.Items))
@@ -1085,9 +1138,10 @@ func (bot *TipBot) shopsHandler(ctx context.Context, m *tb.Message) (context.Con
}
// shopsDeleteShopBrowser is invoked when the user clicks on "delete shops" and makes a list of all shops
func (bot *TipBot) shopsDeleteShopBrowser(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopsDeleteShopBrowser] %s", c.Data)
func (bot *TipBot) shopsDeleteShopBrowser(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[shopsDeleteShopBrowser] %s", c.Data)
shops, err := bot.getUserShops(ctx, user)
if err != nil {
return ctx, err
@@ -1108,8 +1162,9 @@ func (bot *TipBot) shopsDeleteShopBrowser(ctx context.Context, c *tb.Callback) (
return ctx, err
}
func (bot *TipBot) shopsAskDeleteAllShopsHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopsAskDeleteAllShopsHandler] %s", c.Data)
func (bot *TipBot) shopsAskDeleteAllShopsHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
log.WithObjects(ctx).Debugf("[shopsAskDeleteAllShopsHandler] %s", c.Data)
shopResetShopButton := shopKeyboard.Data("⚠️ Delete all shops", "shops_reset", c.Data)
buttons := []tb.Row{
shopKeyboard.Row(shopResetShopButton),
@@ -1123,9 +1178,10 @@ func (bot *TipBot) shopsAskDeleteAllShopsHandler(ctx context.Context, c *tb.Call
}
// shopsLinkShopBrowser is invoked when the user clicks on "shop links" and makes a list of all shops
func (bot *TipBot) shopsLinkShopBrowser(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopsLinkShopBrowser] %s", c.Data)
func (bot *TipBot) shopsLinkShopBrowser(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[shopsLinkShopBrowser] %s", c.Data)
shops, err := bot.getUserShops(ctx, user)
if err != nil {
return ctx, err
@@ -1145,8 +1201,9 @@ func (bot *TipBot) shopsLinkShopBrowser(ctx context.Context, c *tb.Callback) (co
}
// shopSelectLink is invoked when the user has chosen a shop to get the link of
func (bot *TipBot) shopSelectLink(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopSelectLink] %s", c.Data)
func (bot *TipBot) shopSelectLink(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
log.WithObjects(ctx).Debugf("[shopSelectLink] %s", c.Data)
shop, _ := bot.getShop(ctx, c.Data)
if shop.Owner.Telegram.ID != c.Sender.ID {
return ctx, errors.Create(errors.UnknownError)
@@ -1156,9 +1213,10 @@ func (bot *TipBot) shopSelectLink(ctx context.Context, c *tb.Callback) (context.
}
// shopsLinkShopBrowser is invoked when the user clicks on "shop links" and makes a list of all shops
func (bot *TipBot) shopsRenameShopBrowser(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopsRenameShopBrowser] %s", c.Data)
func (bot *TipBot) shopsRenameShopBrowser(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[shopsRenameShopBrowser] %s", c.Data)
shops, err := bot.getUserShops(ctx, user)
if err != nil {
return ctx, err
@@ -1178,9 +1236,10 @@ func (bot *TipBot) shopsRenameShopBrowser(ctx context.Context, c *tb.Callback) (
}
// shopSelectLink is invoked when the user has chosen a shop to get the link of
func (bot *TipBot) shopSelectRename(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopSelectRename] %s", c.Data)
func (bot *TipBot) shopSelectRename(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[shopSelectRename] %s", c.Data)
shop, _ := bot.getShop(ctx, c.Data)
if shop.Owner.Telegram.ID != c.Sender.ID {
return ctx, errors.Create(errors.UnknownError)
@@ -1192,12 +1251,13 @@ func (bot *TipBot) shopSelectRename(ctx context.Context, c *tb.Callback) (contex
}
// shopsDescriptionHandler is invoked when the user clicks on "description" to set a shop description
func (bot *TipBot) shopsDescriptionHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopsDescriptionHandler] %s", c.Data)
func (bot *TipBot) shopsDescriptionHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[shopsDescriptionHandler] %s", c.Data)
shops, err := bot.getUserShops(ctx, user)
if err != nil {
log.Errorf("[shopsDescriptionHandler] %s", err.Error())
log.WithObjects(ctx, user, err).Errorf("[shopsDescriptionHandler] %s", err.Error())
return ctx, err
}
SetUserState(user, bot, lnbits.UserEnterShopsDescription, shops.ID)
@@ -1206,12 +1266,13 @@ func (bot *TipBot) shopsDescriptionHandler(ctx context.Context, c *tb.Callback)
}
// enterShopsDescriptionHandler is invoked when the user enters the shop title
func (bot *TipBot) enterShopsDescriptionHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
log.Debugf("[enterShopsDescriptionHandler] %s", m.Text)
func (bot *TipBot) enterShopsDescriptionHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[enterShopsDescriptionHandler] %s", m.Text)
shops, err := bot.getUserShops(ctx, user)
if err != nil {
log.Errorf("[enterShopsDescriptionHandler] %s", err.Error())
log.WithObjects(ctx, user, err).Errorf("[enterShopsDescriptionHandler] %s", err.Error())
return ctx, err
}
if shops.Owner.Telegram.ID != m.Sender.ID {
@@ -1239,18 +1300,19 @@ func (bot *TipBot) enterShopsDescriptionHandler(ctx context.Context, m *tb.Messa
// time.Sleep(time.Duration(5) * time.Second)
// bot.shopViewDeleteAllStatusMsgs(ctx, user)
// }()
bot.shopsHandler(ctx, m)
bot.shopsHandler(ctx)
bot.tryDeleteMessage(m)
return ctx, nil
}
// shopsResetHandler is invoked when the user clicks button to reset shops completely
func (bot *TipBot) shopsResetHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopsResetHandler] %s", c.Data)
func (bot *TipBot) shopsResetHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[shopsResetHandler] %s", c.Data)
shops, err := bot.getUserShops(ctx, user)
if err != nil {
log.Errorf("[shopsResetHandler] %s", err.Error())
log.WithObjects(ctx, user, err).Errorf("[shopsResetHandler] %s", err.Error())
return ctx, err
}
if shops.Owner.Telegram.ID != c.Sender.ID {
@@ -1262,14 +1324,15 @@ func (bot *TipBot) shopsResetHandler(ctx context.Context, c *tb.Callback) (conte
// time.Sleep(time.Duration(5) * time.Second)
// bot.shopViewDeleteAllStatusMsgs(ctx, user)
// }()
return bot.shopsHandlerCallback(ctx, c)
return bot.shopsHandlerCallback(ctx)
}
// shopSelect is invoked when the user has selected a shop to browse
func (bot *TipBot) shopSelect(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopSelect] %s", c.Data)
func (bot *TipBot) shopSelect(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
shop, _ := bot.getShop(ctx, c.Data)
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[shopSelect] %s", c.Data)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
shopView = ShopView{
@@ -1291,16 +1354,17 @@ func (bot *TipBot) shopSelect(ctx context.Context, c *tb.Callback) (context.Cont
// shopMessage = bot.tryEditMessage(c.Message, "There are no items in this shop yet.", bot.shopMenu(ctx, shop, &ShopItem{}))
// }
shopView.Message = shopMessage
log.Infof("[🛍 shop] %s erntering shop %s.", GetUserStr(user.Telegram), shop.ID)
ctx = context.WithValue(ctx, "callback_response", fmt.Sprintf("🛍 You are browsing %s", shop.Title))
log.WithObjects(ctx, user, err).Infof("[🛍 shop] %s erntering shop %s.", GetUserStr(user.Telegram), shop.ID)
ctx.Context = context.WithValue(ctx, "callback_response", fmt.Sprintf("🛍 You are browsing %s", shop.Title))
return ctx, bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
}
// shopSelectDelete is invoked when the user has chosen a shop to delete
func (bot *TipBot) shopSelectDelete(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopSelectDelete] %s", c.Data)
func (bot *TipBot) shopSelectDelete(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
shop, _ := bot.getShop(ctx, c.Data)
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[shopSelectDelete] %s", c.Data)
shops, err := bot.getUserShops(ctx, user)
if err != nil {
return ctx, err
@@ -1321,15 +1385,16 @@ func (bot *TipBot) shopSelectDelete(ctx context.Context, c *tb.Callback) (contex
// then, delete shop
runtime.IgnoreError(shop.Delete(shop, bot.ShopBunt))
log.Infof("[🛍 shop] %s deleted shop %s.", GetUserStr(user.Telegram), shop.ID)
log.WithObjects(ctx, user).Infof("[🛍 shop] %s deleted shop %s.", GetUserStr(user.Telegram), shop.ID)
// then update buttons
return bot.shopsDeleteShopBrowser(ctx, c)
return bot.shopsDeleteShopBrowser(ctx)
}
// shopsBrowser makes a button list of all shops the user can browse
func (bot *TipBot) shopsBrowser(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopsBrowser] %s", c.Data)
func (bot *TipBot) shopsBrowser(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[shopsBrowser] %s", c.Data)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
return ctx, err
@@ -1356,9 +1421,10 @@ func (bot *TipBot) shopsBrowser(ctx context.Context, c *tb.Callback) (context.Co
}
// shopItemSettingsHandler is invoked when the user presses the shop settings button
func (bot *TipBot) shopSettingsHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopSettingsHandler] %s", c.Data)
func (bot *TipBot) shopSettingsHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[shopSettingsHandler] %s", c.Data)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
return ctx, err
@@ -1368,20 +1434,22 @@ func (bot *TipBot) shopSettingsHandler(ctx context.Context, c *tb.Callback) (con
return ctx, err
}
if shops.ID != c.Data || shops.Owner.Telegram.ID != user.Telegram.ID {
log.Error("[shopSettingsHandler] item id mismatch")
return ctx, errors.Create(errors.ItemIdMismatchError)
err = errors.Create(errors.ItemIdMismatchError)
log.WithObjects(ctx, user, err).Error("[shopSettingsHandler] item id mismatch")
return ctx, err
}
_, err = bot.tryEditMessage(shopView.Message, shopView.Message.Text, bot.shopsSettingsMenu(ctx, shops))
return ctx, err
}
// shopNewShopHandler is invoked when the user presses the new shop button
func (bot *TipBot) shopNewShopHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
log.Debugf("[shopNewShopHandler] %s", c.Data)
func (bot *TipBot) shopNewShopHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[shopNewShopHandler] %s", c.Data)
shops, err := bot.getUserShops(ctx, user)
if err != nil {
log.Errorf("[shopNewShopHandler] %s", err.Error())
log.WithObjects(ctx, user, err).Errorf("[shopNewShopHandler] %s", err.Error())
return ctx, err
}
if len(shops.Shops) >= shops.MaxShops {
@@ -1396,9 +1464,10 @@ func (bot *TipBot) shopNewShopHandler(ctx context.Context, c *tb.Callback) (cont
}
// enterShopTitleHandler is invoked when the user enters the shop title
func (bot *TipBot) enterShopTitleHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
log.Debugf("[enterShopTitleHandler] %s", m.Text)
func (bot *TipBot) enterShopTitleHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user := LoadUser(ctx)
log.WithObjects(ctx, user).Debugf("[enterShopTitleHandler] %s", m.Text)
// read item from user.StateData
shop, err := bot.getShop(ctx, user.StateData)
if err != nil {
@@ -1429,8 +1498,11 @@ func (bot *TipBot) enterShopTitleHandler(ctx context.Context, m *tb.Message) (co
// time.Sleep(time.Duration(5) * time.Second)
// bot.shopViewDeleteAllStatusMsgs(ctx, user)
// }()
bot.shopsHandler(ctx, m)
ctx, err = bot.shopsHandler(ctx)
if err != nil {
log.WithObjects(ctx, user, err).Errorf("[shop] failed shopshandler")
}
bot.tryDeleteMessage(m)
log.Infof("[🛍 shop] %s added new shop %s.", GetUserStr(user.Telegram), shop.ID)
log.WithObjects(ctx, user).Infof("[🛍 shop] %s added new shop %s.", GetUserStr(user.Telegram), shop.ID)
return ctx, nil
}
+18 -20
View File
@@ -1,22 +1,20 @@
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/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/eko/gocache/store"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
func (bot TipBot) shopsMainMenu(ctx context.Context, shops *Shops) *tb.ReplyMarkup {
func (bot TipBot) shopsMainMenu(ctx intercept.Context, shops *Shops) *tb.ReplyMarkup {
browseShopButton := shopKeyboard.Data("🛍 Browse shops", "shops_browse", shops.ID)
shopNewShopButton := shopKeyboard.Data("✅ New Shop", "shops_newshop", shops.ID)
shopSettingsButton := shopKeyboard.Data("⚙️ Settings", "shops_settings", shops.ID)
@@ -35,7 +33,7 @@ func (bot TipBot) shopsMainMenu(ctx context.Context, shops *Shops) *tb.ReplyMark
return shopKeyboard
}
func (bot TipBot) shopsSettingsMenu(ctx context.Context, shops *Shops) *tb.ReplyMarkup {
func (bot TipBot) shopsSettingsMenu(ctx intercept.Context, shops *Shops) *tb.ReplyMarkup {
shopShopsButton := shopKeyboard.Data("⬅️ Back", "shops_shops", shops.ID)
shopLinkShopButton := shopKeyboard.Data("🔗 Shop links", "shops_linkshop", shops.ID)
shopRenameShopButton := shopKeyboard.Data("⌨️ Rename a shop", "shops_renameshop", shops.ID)
@@ -66,7 +64,7 @@ func (bot TipBot) shopsSettingsMenu(ctx context.Context, shops *Shops) *tb.Reply
}
// shopItemSettingsMenu builds the buttons of the item settings
func (bot TipBot) shopItemSettingsMenu(ctx context.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
func (bot TipBot) shopItemSettingsMenu(ctx intercept.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
shopItemPriceButton = shopKeyboard.Data("💯 Set price", "shop_itemprice", item.ID)
shopItemDeleteButton = shopKeyboard.Data("🚫 Delete item", "shop_itemdelete", item.ID)
shopItemTitleButton = shopKeyboard.Data("⌨️ Set title", "shop_itemtitle", item.ID)
@@ -86,7 +84,7 @@ func (bot TipBot) shopItemSettingsMenu(ctx context.Context, shop *Shop, item *Sh
}
// shopItemConfirmBuyMenu builds the buttons to confirm a purchase
func (bot TipBot) shopItemConfirmBuyMenu(ctx context.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
func (bot TipBot) shopItemConfirmBuyMenu(ctx intercept.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
shopItemBuyButton = shopKeyboard.Data(fmt.Sprintf("💸 Pay %d sat", item.Price), "shop_itembuy", item.ID)
shopItemCancelBuyButton = shopKeyboard.Data("⬅️ Back", "shop_itemcancelbuy", item.ID)
buttons := []tb.Row{}
@@ -99,7 +97,7 @@ func (bot TipBot) shopItemConfirmBuyMenu(ctx context.Context, shop *Shop, item *
}
// shopMenu builds the buttons in the item browser
func (bot TipBot) shopMenu(ctx context.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
func (bot TipBot) shopMenu(ctx intercept.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
user := LoadUser(ctx)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
@@ -152,7 +150,7 @@ func (bot *TipBot) makseShopSelectionButtons(shops []*Shop, uniqueString string)
// -------------- ShopView --------------
// getUserShopview returns ShopView object from cache that holds information about the user's current browsing view
func (bot *TipBot) getUserShopview(ctx context.Context, user *lnbits.User) (shopView ShopView, err error) {
func (bot *TipBot) getUserShopview(ctx intercept.Context, user *lnbits.User) (shopView ShopView, err error) {
sv, err := bot.Cache.Get(fmt.Sprintf("shopview-%d", user.Telegram.ID))
if err != nil {
return
@@ -160,7 +158,7 @@ func (bot *TipBot) getUserShopview(ctx context.Context, user *lnbits.User) (shop
shopView = sv.(ShopView)
return
}
func (bot *TipBot) shopViewDeleteAllStatusMsgs(ctx context.Context, user *lnbits.User) (shopView ShopView, err error) {
func (bot *TipBot) shopViewDeleteAllStatusMsgs(ctx intercept.Context, user *lnbits.User) (shopView ShopView, err error) {
mutex.Lock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
defer mutex.Unlock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
shopView, err = bot.getUserShopview(ctx, user)
@@ -182,7 +180,7 @@ func deleteStatusMessages(messages []*tb.Message, bot *TipBot) {
// 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) {
func (bot *TipBot) sendStatusMessage(ctx intercept.Context, to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
user := LoadUser(ctx)
id := fmt.Sprintf("shopview-delete-%d", user.Telegram.ID)
@@ -201,7 +199,7 @@ func (bot *TipBot) sendStatusMessage(ctx context.Context, to tb.Recipient, what
// 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) {
func (bot *TipBot) sendStatusMessageAndDelete(ctx intercept.Context, to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
user := LoadUser(ctx)
id := fmt.Sprintf("shopview-delete-%d", user.Telegram.ID)
statusMsg := bot.sendStatusMessage(ctx, to, what, options...)
@@ -222,7 +220,7 @@ func (bot *TipBot) sendStatusMessageAndDelete(ctx context.Context, to tb.Recipie
// --------------- 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) {
func (bot *TipBot) initUserShops(ctx intercept.Context, user *lnbits.User) (*Shops, error) {
id := fmt.Sprintf("shops-%d", user.Telegram.ID)
shops := &Shops{
Base: storage.New(storage.ID(id)),
@@ -235,11 +233,11 @@ func (bot *TipBot) initUserShops(ctx context.Context, user *lnbits.User) (*Shops
}
// getUserShops returns the Shops for the user
func (bot *TipBot) getUserShops(ctx context.Context, user *lnbits.User) (*Shops, error) {
func (bot *TipBot) getUserShops(ctx intercept.Context, user *lnbits.User) (*Shops, error) {
tx := &Shops{Base: storage.New(storage.ID(fmt.Sprintf("shops-%d", user.Telegram.ID)))}
sn, err := tx.Get(tx, bot.ShopBunt)
if err != nil {
log.Errorf("[getUserShops] User: %s (%d): %s", GetUserStr(user.Telegram), user.Telegram.ID, err)
log.Errorf("[getUserShops] User: %s (%d): %s", user.GetUserStr(), user.Telegram.ID, err)
return &Shops{}, err
}
shops := sn.(*Shops)
@@ -247,7 +245,7 @@ func (bot *TipBot) getUserShops(ctx context.Context, user *lnbits.User) (*Shops,
}
// addUserShop adds a new Shop to the Shops of a user
func (bot *TipBot) addUserShop(ctx context.Context, user *lnbits.User) (*Shop, error) {
func (bot *TipBot) addUserShop(ctx intercept.Context, user *lnbits.User) (*Shop, error) {
shops, err := bot.getUserShops(ctx, user)
if err != nil {
return &Shop{}, err
@@ -270,7 +268,7 @@ func (bot *TipBot) addUserShop(ctx context.Context, user *lnbits.User) (*Shop, e
}
// getShop returns the Shop of a given ID
func (bot *TipBot) getShop(ctx context.Context, shopId string) (*Shop, error) {
func (bot *TipBot) getShop(ctx intercept.Context, shopId string) (*Shop, error) {
tx := &Shop{Base: storage.New(storage.ID(shopId))}
// immediatelly set intransaction to block duplicate calls
sn, err := tx.Get(tx, bot.ShopBunt)
+31 -26
View File
@@ -7,6 +7,8 @@ import (
"strconv"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal"
@@ -15,34 +17,46 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/str"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
"gorm.io/gorm"
)
func (bot TipBot) startHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
if !m.Private() {
func (bot TipBot) startHandler(ctx intercept.Context) (intercept.Context, error) {
if !ctx.Message().Private() {
return ctx, errors.Create(errors.NoPrivateChatError)
}
// ATTENTION: DO NOT CALL ANY HANDLER BEFORE THE WALLET IS CREATED
// WILL RESULT IN AN ENDLESS LOOP OTHERWISE
// bot.helpHandler(m)
log.Printf("[⭐️ /start] New user: %s (%d)\n", GetUserStr(m.Sender), m.Sender.ID)
walletCreationMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "startSettingWalletMessage"))
user, err := bot.initWallet(m.Sender)
log.WithFields(log.Fields{
"module": "telegram",
"func": "startHandler",
"path": "/start",
"user": GetUserStr(ctx.Sender()),
"user_id": ctx.Sender().ID,
}).Printf(" New user")
walletCreationMsg := bot.trySendMessageEditable(ctx.Sender(), Translate(ctx, "startSettingWalletMessage"))
user, err := bot.initWallet(ctx.Sender())
if err != nil {
log.Errorln(fmt.Sprintf("[startHandler] Error with initWallet: %s", err.Error()))
log.WithFields(log.Fields{
"module": "telegram",
"func": "startHandler",
"path": "/start",
"user": GetUserStr(ctx.Sender()),
"user_id": ctx.Sender().ID,
}).Errorln(fmt.Sprintf("Error with initWallet: %s", err.Error()))
bot.tryEditMessage(walletCreationMsg, Translate(ctx, "startWalletErrorMessage"))
return ctx, err
}
bot.tryDeleteMessage(walletCreationMsg)
ctx = context.WithValue(ctx, "user", user)
bot.helpHandler(ctx, m)
bot.trySendMessage(m.Sender, Translate(ctx, "startWalletReadyMessage"))
bot.balanceHandler(ctx, m)
ctx.Context = context.WithValue(ctx, "user", user)
bot.helpHandler(ctx)
bot.trySendMessage(ctx.Sender(), Translate(ctx, "startWalletReadyMessage"))
bot.balanceHandler(ctx)
// send the user a warning about the fact that they need to set a username
if len(m.Sender.Username) == 0 {
bot.trySendMessage(m.Sender, Translate(ctx, "startNoUsernameMessage"), tb.NoPreview)
if len(ctx.Sender().Username) == 0 {
bot.trySendMessage(ctx.Sender(), Translate(ctx, "startNoUsernameMessage"), tb.NoPreview)
}
return ctx, nil
}
@@ -60,7 +74,6 @@ func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
user.Initialized = true
err = UpdateUserRecord(user, bot)
if err != nil {
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
return user, err
}
} else if !user.Initialized {
@@ -69,28 +82,24 @@ func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
user.Initialized = true
err = UpdateUserRecord(user, bot)
if err != nil {
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
return user, err
}
} else if user.Initialized {
// wallet is already initialized
return user, nil
} else {
err = fmt.Errorf("could not initialize wallet")
return user, err
return user, fmt.Errorf("could not initialize wallet")
}
return user, nil
}
func (bot TipBot) createWallet(user *lnbits.User) error {
UserStr := GetUserStr(user.Telegram)
UserStr := user.GetUserStr()
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.Error())
log.Errorln(errormsg)
return err
}
user.Wallet = &lnbits.Wallet{}
@@ -98,22 +107,18 @@ 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.Error())
log.Errorln(errormsg)
return err
}
user.Wallet = &wallet[0]
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
user.AnonIDSha256 = str.AnonIdSha256(user)
user.UUID = str.UUIDSha256(user)
user.AnonIDSha256 = user.AnonIdSha256()
user.UUID = user.UUIDSha256()
user.Initialized = false
user.CreatedAt = time.Now()
err = UpdateUserRecord(user, bot)
if err != nil {
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err.Error())
log.Errorln(errormsg)
return err
}
return nil
+3 -3
View File
@@ -1,12 +1,11 @@
package telegram
import (
"context"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
tb "gopkg.in/lightningtipbot/telebot.v2"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
)
type StateCallbackMessage map[lnbits.UserStateKey]func(ctx context.Context, m *tb.Message) (context.Context, error)
type StateCallbackMessage map[lnbits.UserStateKey]func(ctx intercept.Context) (intercept.Context, error)
var stateCallbackMessage StateCallbackMessage
@@ -21,5 +20,6 @@ func initializeStateCallbackMessage(bot *TipBot) {
lnbits.UserStateShopItemSendTitle: bot.enterShopItemTitleHandler,
lnbits.UserStateShopItemSendItemFile: bot.addItemFileHandler,
lnbits.UserEnterShopsDescription: bot.enterShopsDescriptionHandler,
lnbits.UserEnterDallePrompt: bot.confirmGenerateImages,
}
}
+99 -13
View File
@@ -2,13 +2,15 @@ package telegram
import (
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/log"
"strconv"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/rate"
"github.com/eko/gocache/store"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
"github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// getChatIdFromRecipient will parse the recipient to int64
@@ -25,12 +27,18 @@ func (bot TipBot) tryForwardMessage(to tb.Recipient, what tb.Editable, options .
// ChatId is used for the keyboard
chatId, err := bot.getChatIdFromRecipient(to)
if err != nil {
log.Errorf("[tryForwardMessage] error converting message recipient to int64: %v", err)
log.WithObjects(err).WithFields(logrus.Fields{
"module": "telegram",
"func": "tryForwardMessage",
"user": to.Recipient()}).Errorf("error converting message recipient to int64")
return
}
msg, err = bot.Telegram.Forward(to, what, bot.appendMainMenu(chatId, to, options)...)
if err != nil {
log.Warnln(err.Error())
log.WithObjects(err).WithFields(logrus.Fields{
"module": "telegram",
"func": "tryForwardMessage",
"user": to.Recipient()}).Warnln("error forwarding message")
}
return
}
@@ -39,13 +47,23 @@ func (bot TipBot) trySendMessage(to tb.Recipient, what interface{}, options ...i
// ChatId is used for the keyboard
chatId, err := bot.getChatIdFromRecipient(to)
if err != nil {
log.Errorf("[trySendMessage] error converting message recipient to int64: %v", err)
log.WithObjects(err).WithFields(logrus.Fields{
"module": "telegram",
"func": "trySendMessage",
"user": to.Recipient()}).Errorf("[trySendMessage] error converting message recipient to int64: %v", err)
return
}
log.Tracef("[trySendMessage] chatId: %d", chatId)
logrus.WithFields(logrus.Fields{
"module": "telegram",
"func": "trySendMessage",
"chat_id": chatId,
"user": to.Recipient()}).Tracef("trying to send something")
msg, err = bot.Telegram.Send(to, what, bot.appendMainMenu(chatId, to, options)...)
if err != nil {
log.Warnln(err.Error())
log.WithObjects(err).WithFields(logrus.Fields{
"module": "telegram",
"func": "trySendMessage",
"user": to.Recipient()}).Warnln("error sending message")
}
return
}
@@ -54,7 +72,10 @@ func (bot TipBot) trySendMessageEditable(to tb.Recipient, what interface{}, opti
rate.CheckLimit(to)
msg, err := bot.Telegram.Send(to, what, options...)
if err != nil {
log.Warnln(err.Error())
log.WithObjects(err).WithFields(logrus.Fields{
"module": "telegram",
"func": "trySendMessageEditable",
"user": to.Recipient()}).Warnln("error sending editable")
}
return
}
@@ -63,7 +84,9 @@ func (bot TipBot) tryReplyMessage(to *tb.Message, what interface{}, options ...i
rate.CheckLimit(to)
msg, err := bot.Telegram.Reply(to, what, bot.appendMainMenu(to.Chat.ID, to, options)...)
if err != nil {
log.Warnln(err.Error())
log.WithObjects(err, &lnbits.User{Telegram: to.Sender}).WithFields(logrus.Fields{
"module": "telegram",
"func": "trySendMessageEditable"}).Warnln("error reply message")
}
return
}
@@ -77,10 +100,15 @@ func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...in
rate.CheckLimit(sig)
_, chatId := to.MessageSig()
log.Tracef("[tryEditMessage] sig: %s, chatId: %d", sig, chatId)
logrus.WithFields(logrus.Fields{
"module": "telegram",
"func": "tryEditMessage",
"chat_id": chatId}).Tracef("trying to send something")
msg, err = bot.Telegram.Edit(to, what, options...)
if err != nil {
log.Warnln(err.Error())
log.WithObjects(err).WithFields(logrus.Fields{
"module": "telegram",
"func": "tryEditMessage"}).Warnln("error edit message")
}
return
}
@@ -92,7 +120,9 @@ func (bot TipBot) tryDeleteMessage(msg tb.Editable) {
rate.CheckLimit(msg)
err := bot.Telegram.Delete(msg)
if err != nil {
log.Warnln(err.Error())
log.WithObjects(err).WithFields(logrus.Fields{
"module": "telegram",
"func": "tryDeleteMessage"}).Warnln("error delete message")
}
return
@@ -114,7 +144,9 @@ func allowedToPerformAction(bot TipBot, editable tb.Editable, action func(member
if err != nil {
admins, err = bot.Telegram.AdminsOf(message.Chat)
if err != nil {
log.Warnln(err.Error())
log.WithObjects(err).WithFields(logrus.Fields{
"module": "telegram",
"func": "allowedToPerformAction"}).Warnln("error fetching admins")
return false
}
bot.Cache.Set(fmt.Sprintf("admins-%d", chat.ID), admins, &store.Options{Expiration: 5 * time.Minute})
@@ -137,3 +169,57 @@ func isAdminAndCanDelete(members []tb.ChatMember, me *tb.User) bool {
}
return false
}
// isOwner will check if user is owner of group
func (bot *TipBot) isOwner(chat *tb.Chat, me *tb.User) bool {
members, err := bot.Telegram.AdminsOf(chat)
if err != nil {
log.WithObjects(err).WithFields(logrus.Fields{
"module": "telegram",
"func": "isOwner",
"chat_id": chat.ID}).Warnln("error checking bot admin status")
return false
}
for _, admin := range members {
if admin.User.ID == me.ID && admin.Role == "creator" {
return true
}
}
return false
}
// isAdmin will check if user is admin in a group
func (bot *TipBot) isAdmin(chat *tb.Chat, me *tb.User) bool {
members, err := bot.Telegram.AdminsOf(chat)
if err != nil {
log.WithObjects(err).WithFields(logrus.Fields{
"module": "telegram",
"func": "isAdmin",
"chat_id": chat.ID}).Warnln("error checking bot admin status")
return false
}
for _, admin := range members {
if admin.User.ID == me.ID {
return true
}
}
return false
}
// isAdmin will check if user is admin in a group
func (bot *TipBot) isAdminAndCanInviteUsers(chat *tb.Chat, me *tb.User) bool {
members, err := bot.Telegram.AdminsOf(chat)
if err != nil {
log.WithObjects(err).WithFields(logrus.Fields{
"module": "telegram",
"func": "isAdminAndCanInviteUsers",
"chat_id": chat.ID}).Warnln("error checking bot admin status")
return false
}
for _, admin := range members {
if admin.User.ID == me.ID {
return admin.CanInviteUsers
}
}
return false
}
+23 -12
View File
@@ -4,16 +4,19 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
func (bot *TipBot) anyTextHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
func (bot *TipBot) anyTextHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
if m.Chat.Type != tb.ChatPrivate {
return ctx, errors.Create(errors.NoPrivateChatError)
}
@@ -21,7 +24,7 @@ func (bot *TipBot) anyTextHandler(ctx context.Context, m *tb.Message) (context.C
// check if user is in Database, if not, initialize wallet
user := LoadUser(ctx)
if user.Wallet == nil || !user.Initialized {
return bot.startHandler(ctx, m)
return bot.startHandler(ctx)
}
// check if the user clicked on the balance button
@@ -30,21 +33,21 @@ func (bot *TipBot) anyTextHandler(ctx context.Context, m *tb.Message) (context.C
// overwrite the message text so it doesn't cause an infinite loop
// because balanceHandler calls anyTextHAndler...
m.Text = ""
return bot.balanceHandler(ctx, m)
return bot.balanceHandler(ctx)
}
// could be an invoice
anyText := strings.ToLower(m.Text)
if lightning.IsInvoice(anyText) {
m.Text = "/pay " + anyText
return bot.payHandler(ctx, m)
return bot.payHandler(ctx)
}
if lightning.IsLnurl(anyText) {
m.Text = "/lnurl " + anyText
return bot.lnurlHandler(ctx, m)
return bot.lnurlHandler(ctx)
}
if c := stateCallbackMessage[user.StateKey]; c != nil {
return c(ctx, m)
return c(ctx)
//ResetUserState(user, bot)
}
return ctx, nil
@@ -83,8 +86,9 @@ func (bot *TipBot) askForUser(ctx context.Context, id string, eventType string,
// enterAmountHandler is invoked in anyTextHandler when the user needs to enter an amount
// the amount is then stored as an entry in the user's stateKey in the user database
// any other handler that relies on this, needs to load the resulting amount from the database
func (bot *TipBot) enterUserHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
// any other ctx that relies on this, needs to load the resulting amount from the database
func (bot *TipBot) enterUserHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
@@ -102,7 +106,14 @@ func (bot *TipBot) enterUserHandler(ctx context.Context, m *tb.Message) (context
var EnterUserStateData EnterUserStateData
err := json.Unmarshal([]byte(user.StateData), &EnterUserStateData)
if err != nil {
log.Errorf("[EnterUserHandler] %s", err.Error())
log.WithFields(log.Fields{
"module": "telegram",
"func": "lnurlPayHandlerSend",
"user": user.GetUserStr(),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"telegram_id": user.Telegram.ID,
"error": err}).Errorf("error unmarshaling state data")
ResetUserState(user, bot)
return ctx, err
}
@@ -114,7 +125,7 @@ func (bot *TipBot) enterUserHandler(ctx context.Context, m *tb.Message) (context
switch EnterUserStateData.Type {
case "CreateSendState":
m.Text = fmt.Sprintf("/send %s", userstr)
return bot.sendHandler(ctx, m)
return bot.sendHandler(ctx)
default:
ResetUserState(user, bot)
return ctx, errors.Create(errors.InvalidSyntaxError)
+39 -21
View File
@@ -3,16 +3,19 @@ package telegram
import (
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/log"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
logrus "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
func helpTipUsage(ctx context.Context, errormsg string) string {
@@ -31,9 +34,10 @@ func TipCheckSyntax(ctx context.Context, m *tb.Message) (bool, string) {
return true, ""
}
func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
func (bot *TipBot) tipHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
// check and print all commands
bot.anyTextHandler(ctx, m)
bot.anyTextHandler(ctx)
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, fmt.Errorf("user has no wallet")
@@ -52,21 +56,26 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) (context.Conte
NewMessage(m, WithDuration(0, bot))
return ctx, errors.Create(errors.InvalidSyntaxError)
}
logFields := logrus.Fields{
"module": "telegram",
"func": "tipHandler",
"path": "/tip",
}
// get tip amount
amount, err := decodeAmountFromCommand(m.Text)
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))
bot.trySendMessage(m.Sender, helpTipUsage(ctx, Translate(ctx, "tipValidAmountMessage")))
log.Warnln(errmsg)
return ctx, errors.Create(errors.InvalidAmountError)
err = fmt.Errorf("%v: %v", errors.Create(errors.InvalidAmountError), err)
log.WithObjects(ctx, user, err).WithFields(logFields).Warnln(err.Error())
return ctx, err
}
err = bot.parseCmdDonHandler(ctx, m)
err = bot.parseDonationCommandHandler(ctx)
if err == nil {
return ctx, fmt.Errorf("invalid parseCmdDonHandler")
log.WithObjects(ctx, user, err).WithFields(logFields).WithField("amount", amount).Warnln("failed parsing donation command")
return ctx, err
}
// TIP COMMAND IS VALID
from := LoadUser(ctx)
@@ -84,12 +93,17 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) (context.Conte
fromUserStr := GetUserStr(from.Telegram)
if _, exists := bot.UserExists(to.Telegram); !exists {
log.Infof("[/tip] User %s has no wallet.", toUserStr)
log.WithObjects(ctx, user).WithFields(logFields).WithFields(logrus.Fields{
"to_user": toUserStr,
"to_user_id": to.ID}).Infof("User has no wallet.")
to, err = bot.CreateWalletForTelegramUser(to.Telegram)
if err != nil {
errmsg := fmt.Errorf("[/tip] Error: Could not create wallet for %s", toUserStr)
log.Errorln(errmsg)
return ctx, fmt.Errorf("could not create wallet for %s", toUserStr)
log.WithObjects(ctx, user, err).WithFields(logFields).WithFields(logrus.Fields{
"to_user": GetUserStr(to.Telegram),
"to_user_id": to.ID,
"to_wallet_id": to.Wallet.ID,
}).Errorln("Could not create wallet for user")
return ctx, err
}
}
@@ -104,22 +118,26 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) (context.Conte
}
// todo: user new get username function to get userStrings
transactionMemo := fmt.Sprintf("Tip from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
transactionMemo := fmt.Sprintf("🏅 Tip from %s to %s.", fromUserStr, toUserStr)
t := NewTransaction(bot, from, to, amount, TransactionType("tip"), TransactionChat(m.Chat))
t.Memo = transactionMemo
success, err := t.Send()
if !success {
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, fmt.Sprintf("%s %s", Translate(ctx, "tipErrorMessage"), err))
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err.Error())
log.Warnln(errMsg)
return ctx, fmt.Errorf("could not create wallet for %s", toUserStr)
bot.trySendMessage(m.Sender, fmt.Sprintf("%s: %s", Translate(ctx, "tipErrorMessage"), Translate(ctx, "tipUndefinedErrorMsg")))
log.WithObjects(ctx, user, err).WithFields(logFields).WithFields(logrus.Fields{
"to_user": toUserStr,
"to_user_id": to.ID,
}).Warnf("Transaction failed")
return ctx, err
}
// update tooltip if necessary
messageHasTip := tipTooltipHandler(m, bot, amount, to.Initialized)
log.Infof("[💸 tip] Tip from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
log.WithObjects(ctx, user).WithFields(logFields).WithFields(logrus.Fields{
"to_user": toUserStr,
"amount": amount}).Info("created Tip")
// notify users
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "tipSentMessage"), amount, toUserStrMd))
+106 -31
View File
@@ -6,6 +6,8 @@ import (
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
@@ -16,11 +18,11 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
var (
inlineTipjarMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: false}
inlineTipjarMenu = &tb.ReplyMarkup{ResizeKeyboard: false}
btnCancelInlineTipjar = inlineTipjarMenu.Data("🚫", "cancel_tipjar_inline")
btnAcceptInlineTipjar = inlineTipjarMenu.Data("💸 Pay", "confirm_tipjar_inline")
)
@@ -56,7 +58,7 @@ func (bot TipBot) createTipjar(ctx context.Context, text string, sender *tb.User
if err != nil {
return nil, errors.New(errors.DecodePerUserAmountError, err)
}
perUserAmount, err := getAmount(peruserStr)
perUserAmount, err := GetAmount(peruserStr)
if err != nil {
return nil, errors.New(errors.InvalidAmountError, err)
}
@@ -131,28 +133,27 @@ func (bot TipBot) makeTipjar(ctx context.Context, m *tb.Message, query bool) (*I
return tipjar, err
}
func (bot TipBot) makeQueryTipjar(ctx context.Context, q *tb.Query, query bool) (*InlineTipjar, error) {
tipjar, err := bot.createTipjar(ctx, q.Text, &q.From)
func (bot TipBot) makeQueryTipjar(ctx intercept.Context) (*InlineTipjar, error) {
tipjar, err := bot.createTipjar(ctx, ctx.Query().Text, ctx.Query().Sender)
if err != nil {
switch err.(errors.TipBotError).Code {
case errors.DecodeAmountError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.DecodePerUserAmountError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.InvalidAmountError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.InvalidAmountPerUserError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineTipjarInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineTipjarInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.GetBalanceError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.BalanceToLowError:
log.Errorf(err.Error())
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
bot.inlineQueryReplyWithError(ctx, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
return nil, err
}
}
@@ -160,7 +161,7 @@ func (bot TipBot) makeQueryTipjar(ctx context.Context, q *tb.Query, query bool)
}
func (bot TipBot) makeTipjarKeyboard(ctx context.Context, inlineTipjar *InlineTipjar) *tb.ReplyMarkup {
inlineTipjarMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
inlineTipjarMenu := &tb.ReplyMarkup{ResizeKeyboard: true}
// slice of buttons
buttons := make([]tb.Btn, 0)
cancelInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_tipjar_inline", inlineTipjar.ID)
@@ -173,13 +174,14 @@ func (bot TipBot) makeTipjarKeyboard(ctx context.Context, inlineTipjar *InlineTi
return inlineTipjarMenu
}
func (bot TipBot) tipjarHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
bot.anyTextHandler(ctx, m)
func (bot TipBot) tipjarHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
bot.anyTextHandler(ctx)
if m.Private() {
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineTipjarHelpText"), Translate(ctx, "inlineTipjarHelpTipjarInGroup")))
return ctx, errors.Create(errors.NoPrivateChatError)
}
ctx = bot.mapTipjarLanguage(ctx, m.Text)
ctx.Context = bot.mapTipjarLanguage(ctx, m.Text)
inlineTipjar, err := bot.makeTipjar(ctx, m, false)
if err != nil {
log.Errorf("[tipjar] %s", err.Error())
@@ -191,8 +193,9 @@ func (bot TipBot) tipjarHandler(ctx context.Context, m *tb.Message) (context.Con
return ctx, inlineTipjar.Set(inlineTipjar, bot.Bunt)
}
func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) (context.Context, error) {
inlineTipjar, err := bot.makeQueryTipjar(ctx, q, false)
func (bot TipBot) handleInlineTipjarQuery(ctx intercept.Context) (intercept.Context, error) {
q := ctx.Query()
inlineTipjar, err := bot.makeQueryTipjar(ctx)
if err != nil {
// log.Errorf("[tipjar] %s", err.Error())
return ctx, err
@@ -210,13 +213,22 @@ func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) (con
// required for photos
ThumbURL: url,
}
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeTipjarKeyboard(ctx, inlineTipjar).InlineKeyboard}
result.ReplyMarkup = &tb.ReplyMarkup{InlineKeyboard: bot.makeTipjarKeyboard(ctx, inlineTipjar).InlineKeyboard}
results[i] = result
// needed to set a unique string ID for each result
results[i].SetResultID(inlineTipjar.ID)
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)
log.WithFields(log.Fields{
"module": "telegram-tipjar",
"func": "handleInlineTipjarQuery",
"to_user": GetUserStr(inlineTipjar.To.Telegram),
"to_user_id": inlineTipjar.To.ID,
"to_telegram_id": inlineTipjar.To.Telegram.ID,
"to_wallet_id": inlineTipjar.To.Wallet.ID,
"amount": inlineTipjar.PerUserAmount,
"data": fmt.Sprintf("[tipjar] %s created inline tipjar %s: %d sat (%d per user)", GetUserStr(inlineTipjar.To.Telegram), inlineTipjar.ID, inlineTipjar.Amount, inlineTipjar.PerUserAmount)}).
Infof("created tipjar")
}
err = bot.Telegram.Answer(q, &tb.QueryResponse{
@@ -225,13 +237,16 @@ func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) (con
IsPersonal: true,
})
if err != nil {
log.Errorln(err)
log.WithFields(log.Fields{
"module": "telegram-tipjar",
"func": "handleInlineTipjarQuery"}).Errorln("could not answer query")
return ctx, err
}
return ctx, nil
}
func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
func (bot *TipBot) acceptInlineTipjarHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
from := LoadUser(ctx)
if from.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
@@ -247,7 +262,15 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
inlineTipjar := fn.(*InlineTipjar)
to := inlineTipjar.To
if !inlineTipjar.Active {
log.Errorf(fmt.Sprintf("[tipjar] tipjar %s inactive.", inlineTipjar.ID))
log.WithFields(log.Fields{
"module": "telegram",
"func": "acceptInlineTipjarHandler",
"to_user_id": to.ID,
"user_id": from.ID,
"wallet_id": from.Wallet.ID,
"amount": inlineTipjar.PerUserAmount,
"telegram_id": from.Telegram.ID}).Errorf(fmt.Sprintf("tipjar %s inactive.", inlineTipjar.ID))
bot.tryEditMessage(c, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
return ctx, errors.Create(errors.NotActiveError)
}
@@ -263,6 +286,9 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
return ctx, errors.Create(errors.UnknownError)
}
}
defer inlineTipjar.Set(inlineTipjar, bot.Bunt)
if inlineTipjar.GivenAmount < inlineTipjar.Amount {
toUserStrMd := GetUserStrMd(to.Telegram)
fromUserStrMd := GetUserStrMd(from.Telegram)
@@ -270,7 +296,7 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
fromUserStr := GetUserStr(from.Telegram)
// todo: user new get username function to get userStrings
transactionMemo := fmt.Sprintf("Tipjar from %s to %s (%d sat).", fromUserStr, toUserStr, inlineTipjar.PerUserAmount)
transactionMemo := fmt.Sprintf("🍯 Tipjar from %s to %s.", fromUserStr, toUserStr)
t := NewTransaction(bot, from, to, inlineTipjar.PerUserAmount, TransactionType("tipjar"))
t.Memo = transactionMemo
@@ -282,7 +308,16 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
return ctx, errors.New(errors.UnknownError, err)
}
log.Infof("[💸 tipjar] Tipjar %s from %s to %s (%d sat).", inlineTipjar.ID, fromUserStr, toUserStr, inlineTipjar.PerUserAmount)
log.WithFields(log.Fields{
"module": "telegram",
"func": "acceptInlineTipjarHandler",
"user": fromUserStr,
"to_user": toUserStr,
"to_user_id": to.ID,
"user_id": from.ID,
"wallet_id": from.Wallet.ID,
"amount": inlineTipjar.PerUserAmount,
"telegram_id": from.Telegram.ID}).Infof("Draining tipjar")
inlineTipjar.NGiven += 1
inlineTipjar.From = append(inlineTipjar.From, from)
inlineTipjar.GivenAmount = inlineTipjar.GivenAmount + inlineTipjar.PerUserAmount
@@ -291,7 +326,16 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineTipjarSentMessage"), inlineTipjar.PerUserAmount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[tipjar] Error: Send message to %s: %s", toUserStr, err)
log.Warnln(errmsg)
log.WithFields(log.Fields{
"module": "telegram",
"func": "acceptInlineTipjarHandler",
"user": fromUserStr,
"to_user": toUserStr,
"to_user_id": to.ID,
"user_id": from.ID,
"wallet_id": from.Wallet.ID,
"amount": inlineTipjar.PerUserAmount,
"telegram_id": from.Telegram.ID}).Warnln(errmsg)
}
// build tipjar message
@@ -309,8 +353,17 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
inlineTipjar.Message = inlineTipjar.Message + fmt.Sprintf(i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarAppendMemo"), memo)
}
// update message
log.Infoln(inlineTipjar.Message)
bot.tryEditMessage(c.Message, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
log.WithFields(log.Fields{
"module": "telegram",
"func": "acceptInlineTipjarHandler",
"user": fromUserStr,
"to_user": toUserStr,
"to_user_id": to.ID,
"user_id": from.ID,
"wallet_id": from.Wallet.ID,
"amount": inlineTipjar.PerUserAmount,
"telegram_id": from.Telegram.ID}).Infoln(inlineTipjar.Message)
bot.tryEditMessage(c, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
}
if inlineTipjar.GivenAmount >= inlineTipjar.Amount {
// tipjar is full
@@ -320,14 +373,19 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
inlineTipjar.Amount,
inlineTipjar.NGiven,
)
bot.tryEditMessage(c.Message, inlineTipjar.Message)
bot.tryEditMessage(c, inlineTipjar.Message)
// send update to tipjar creator
if inlineTipjar.Active && inlineTipjar.To.Telegram.ID != 0 {
bot.trySendMessage(inlineTipjar.To.Telegram, listTipjarGivers(inlineTipjar))
}
inlineTipjar.Active = false
}
return ctx, nil
}
func (bot *TipBot) cancelInlineTipjarHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
func (bot *TipBot) cancelInlineTipjarHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
tx := &InlineTipjar{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
@@ -340,8 +398,25 @@ func (bot *TipBot) cancelInlineTipjarHandler(ctx context.Context, c *tb.Callback
if c.Sender.ID != inlineTipjar.To.Telegram.ID {
return ctx, errors.Create(errors.UnknownError)
}
bot.tryEditMessage(c.Message, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
bot.tryEditMessage(c, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
// send update to tipjar creator
if inlineTipjar.Active && inlineTipjar.To.Telegram.ID != 0 {
bot.trySendMessage(inlineTipjar.To.Telegram, listTipjarGivers(inlineTipjar))
}
// set the inlineTipjar inactive
inlineTipjar.Active = false
return ctx, inlineTipjar.Set(inlineTipjar, bot.Bunt)
}
func listTipjarGivers(inlineTipjar *InlineTipjar) string {
var from_str string
from_str = fmt.Sprintf("🍯 *Tipjar summary*\n\nMemo: %s\nCapacity: %d sat\nGivers: %d\nCollected: %d sat\n\n*Givers:*\n\n", inlineTipjar.Memo, inlineTipjar.Amount, inlineTipjar.NGiven, inlineTipjar.GivenAmount)
from_str += "```\n"
for _, from := range inlineTipjar.From {
from_str += fmt.Sprintf("%s\n", GetUserStr(from.Telegram))
}
from_str += "```"
return from_str
}
+1 -1
View File
@@ -13,7 +13,7 @@ import (
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
const (
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"testing"
"time"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
var (
+93 -35
View File
@@ -7,30 +7,30 @@ import (
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
type Transaction struct {
ID uint `gorm:"primarykey"`
Time time.Time `json:"time"`
Bot *TipBot `gorm:"-"`
From *lnbits.User `json:"from" gorm:"-"`
To *lnbits.User `json:"to" gorm:"-"`
FromId 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_"`
ID uint `gorm:"primarykey"`
Time time.Time `json:"time"`
Bot *TipBot `gorm:"-"`
From *lnbits.User `json:"from" gorm:"-"`
To *lnbits.User `json:"to" gorm:"-"`
FromId int64 `json:"from_id" `
ToId int64 `json:"to_id" `
FromUser string `json:"from_user"`
ToUser string `json:"to_user"`
Type string `json:"type"`
Amount int64 `json:"amount"`
ChatID int64 `json:"chat_id"`
ChatName string `json:"chat_name"`
Memo string `json:"memo"`
Success bool `json:"success"`
FromWallet string `json:"from_wallet"`
ToWallet string `json:"to_wallet"`
FromLNbitsID string `json:"from_lnbits"`
ToLNbitsID string `json:"to_lnbits"`
Invoice lnbits.Invoice `gorm:"embedded;embeddedPrefix:invoice_"`
}
type TransactionOption func(t *Transaction)
@@ -76,10 +76,19 @@ func (t *Transaction) Send() (success bool, err error) {
}
// save transaction to db
tx := t.Bot.logger.Save(t)
tx := t.Bot.DB.Transactions.Save(t)
if tx.Error != nil {
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err.Error())
log.Errorln(errMsg)
log.WithFields(log.Fields{
"module": "telegram",
"func": "SendTransaction",
"user": t.FromUser,
"user_id": t.From.ID,
"wallet_id": t.From.Wallet.ID,
"telegram_id": t.From.Telegram.ID,
"to_user": t.ToUser,
"to_wallet_id": t.To.Wallet.ID,
"to_user_id": t.To.ID,
"error": tx.Error}).Errorln("could not log transaction")
}
return success, err
}
@@ -94,14 +103,30 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
// 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)
log.WithFields(log.Fields{
"module": "telegram",
"func": "SendTransaction",
"to_user": toUserStr,
"to_user_id": to.ID,
"to_wallet_id": to.Wallet.ID,
"user": fromUserStr,
"user_id": from.ID,
"wallet_id": from.Wallet.ID,
"amount": amount},
).Errorln("error checking balance")
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)
log.WithFields(log.Fields{
"module": "telegram",
"func": "SendTransaction",
"to_user": to.ID,
"user": fromUserStr,
"user_id": from.ID,
"wallet_id": from.Wallet.ID,
"telegram_id": from.Telegram.ID}).Warn("balance of too low")
return false, fmt.Errorf(errmsg)
}
@@ -116,30 +141,63 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
Memo: memo},
bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[Send] Error: Could not create invoice for user %s", toUserStr)
log.Errorln(errmsg)
log.WithFields(log.Fields{
"module": "telegram",
"func": "SendTransaction",
"user": toUserStr,
"user_id": to.ID,
"wallet_id": to.Wallet.ID,
"telegram_id": to.Telegram.ID,
"error": err.Error()}).Errorln("could not create invoice")
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("[Send] Payment failed (%s to %s of %d sat): %s", fromUserStr, toUserStr, amount, err.Error())
log.Warnf(errmsg)
log.WithFields(log.Fields{
"module": "telegram",
"func": "SendTransaction",
"user": fromUserStr,
"user_id": from.ID,
"wallet_id": from.Wallet.ID,
"telegram_id": from.Telegram.ID,
"to_user": toUserStr,
"to_wallet_id": to.Wallet.ID,
"to_user_id": to.ID,
"error": err.Error()}).Warnf("Payment failed")
return false, err
}
// check if fromUser has balance
_, err = bot.GetUserBalance(from)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
log.Errorln(errmsg)
log.WithFields(log.Fields{
"module": "telegram",
"func": "SendTransaction",
"user": fromUserStr,
"user_id": from.ID,
"wallet_id": from.Wallet.ID,
"telegram_id": from.Telegram.ID,
"to_user": toUserStr,
"to_wallet_id": to.Wallet.ID,
"to_user_id": to.ID,
"error": err.Error()}).Errorln("could not get sender balance")
return false, err
}
_, err = bot.GetUserBalance(to)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
log.Errorln(errmsg)
log.WithFields(log.Fields{
"module": "telegram",
"func": "SendTransaction",
"user": fromUserStr,
"user_id": from.ID,
"wallet_id": from.Wallet.ID,
"telegram_id": from.Telegram.ID,
"to_user": toUserStr,
"to_wallet_id": to.Wallet.ID,
"to_user_id": to.ID,
"error": err.Error()}).Errorln("could not get receiver balance")
return false, err
}
+178
View File
@@ -0,0 +1,178 @@
package telegram
import (
"fmt"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/eko/gocache/store"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
type TransactionsList struct {
ID string `json:"id"`
User *lnbits.User `json:"from"`
Payments lnbits.Payments `json:"payments"`
LanguageCode string `json:"languagecode"`
CurrentPage int `json:"currentpage"`
MaxPages int `json:"maxpages"`
TxPerPage int `json:"txperpage"`
}
func (txlist *TransactionsList) printTransactions(ctx intercept.Context) string {
txstr := ""
// for _, p := range payments {
payments := txlist.Payments
pagenr := txlist.CurrentPage
tx_per_page := txlist.TxPerPage
if pagenr > (len(payments)+1)/tx_per_page {
pagenr = 0
}
if len(payments) < tx_per_page {
tx_per_page = len(payments)
}
start := pagenr * (tx_per_page - 1)
end := start + tx_per_page
if end >= len(payments) {
end = len(payments) - 1
}
for i := start; i <= end; i++ {
p := payments[i]
if p.Pending {
txstr += "🔄"
} else {
if p.Amount < 0 {
txstr += "🔴"
} else {
txstr += "🟢"
}
}
timestr := time.Unix(int64(p.Time), 0).UTC().Format("2 Jan 06 15:04")
txstr += fmt.Sprintf("` %s`", timestr)
txstr += fmt.Sprintf("` %+d sat`", p.Amount/1000)
if p.Fee > 0 {
fee := p.Fee
if fee < 1000 {
fee = 1000
}
txstr += fmt.Sprintf(" _(fee: %d sat)_", fee/1000)
}
memo := p.Memo
memo_maxlen := 50
if len(memo) > memo_maxlen {
memo = memo[:memo_maxlen] + "..."
}
if len(memo) > 0 {
txstr += fmt.Sprintf("\n✉️ %s", str.MarkdownEscape(memo))
}
txstr += "\n"
}
txstr += fmt.Sprintf("\nShowing %d transactions. Page %d of %d.", len(payments), txlist.CurrentPage+1, txlist.MaxPages)
return txstr
}
var (
transactionsMeno = &tb.ReplyMarkup{ResizeKeyboard: true}
btnLeftTransactionsButton = inlineTipjarMenu.Data("◀️", "left_transactions")
btnRightTransactionsButton = inlineTipjarMenu.Data("▶️", "right_transactions")
)
func (bot *TipBot) makeTransactionsKeyboard(ctx intercept.Context, txlist TransactionsList) *tb.ReplyMarkup {
leftTransactionsButton := transactionsMeno.Data("←", "left_transactions", txlist.ID)
rightTransactionsButton := transactionsMeno.Data("→", "right_transactions", txlist.ID)
if txlist.CurrentPage == 0 {
transactionsMeno.Inline(
transactionsMeno.Row(
leftTransactionsButton),
)
} else if txlist.CurrentPage == txlist.MaxPages-1 {
transactionsMeno.Inline(
transactionsMeno.Row(
rightTransactionsButton),
)
} else {
transactionsMeno.Inline(
transactionsMeno.Row(
leftTransactionsButton,
rightTransactionsButton),
)
}
return transactionsMeno
}
func (bot *TipBot) transactionsHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user := LoadUser(ctx)
payments, err := bot.Client.Payments(*user.Wallet)
if err != nil {
log.Errorf("[transactions] Error: %s", err.Error())
return ctx, err
}
tx_per_page := 10
transactionsList := TransactionsList{
ID: fmt.Sprintf("txlist:%d:%s", user.Telegram.ID, RandStringRunes(5)),
User: user,
Payments: payments,
LanguageCode: ctx.Value("userLanguageCode").(string),
CurrentPage: 0,
TxPerPage: tx_per_page,
MaxPages: (len(payments)+1)/tx_per_page + 1,
}
bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), transactionsList, &store.Options{Expiration: 1 * time.Minute})
txstr := transactionsList.printTransactions(ctx)
bot.trySendMessage(m.Sender, txstr, bot.makeTransactionsKeyboard(ctx, transactionsList))
return ctx, nil
}
func (bot *TipBot) transactionsScrollLeftHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
transactionsListInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
if err != nil {
log.WithFields(log.Fields{
"module": "telegram",
"func": "transactionsScrollLeftHandler",
}).Info("Transactions not in cache anymore")
return ctx, err
}
transactionsList := transactionsListInterface.(TransactionsList)
if c.Sender.ID == transactionsList.User.Telegram.ID {
if transactionsList.CurrentPage < transactionsList.MaxPages-1 {
transactionsList.CurrentPage++
} else {
return ctx, err
}
bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), transactionsList, &store.Options{Expiration: 1 * time.Minute})
bot.tryEditMessage(c.Message, transactionsList.printTransactions(ctx), bot.makeTransactionsKeyboard(ctx, transactionsList))
}
return ctx, nil
}
func (bot *TipBot) transactionsScrollRightHandler(ctx intercept.Context) (intercept.Context, error) {
c := ctx.Callback()
user := LoadUser(ctx)
transactionsListInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
if err != nil {
log.WithFields(log.Fields{
"module": "telegram",
"func": "transactionsScrollRightHandler"}).Info("Transactions not in cache anymore")
return ctx, err
}
transactionsList := transactionsListInterface.(TransactionsList)
if c.Sender.ID == transactionsList.User.Telegram.ID {
if transactionsList.CurrentPage > 0 {
transactionsList.CurrentPage--
} else {
return ctx, nil
}
bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), transactionsList, &store.Options{Expiration: 1 * time.Minute})
bot.tryEditMessage(c.Message, transactionsList.printTransactions(ctx), bot.makeTransactionsKeyboard(ctx, transactionsList))
}
return ctx, nil
}
+25 -31
View File
@@ -7,10 +7,9 @@ import (
"time"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/eko/gocache/store"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
tb "gopkg.in/lightningtipbot/telebot.v3"
"gorm.io/gorm"
)
@@ -25,33 +24,13 @@ func ResetUserState(user *lnbits.User, bot *TipBot) {
user.ResetState()
UpdateUserRecord(user, *bot)
}
func GetUserStr(user *tb.User) string {
userStr := fmt.Sprintf("@%s", user.Username)
// if user does not have a username
if len(userStr) < 2 && user.FirstName != "" {
userStr = fmt.Sprintf("%s", user.FirstName)
} else if len(userStr) < 2 {
userStr = fmt.Sprintf("%d", user.ID)
}
return userStr
return lnbits.User{Telegram: user}.GetUserStr()
}
func GetUserStrMd(user *tb.User) string {
userStr := fmt.Sprintf("@%s", user.Username)
// if user does not have a username
if len(userStr) < 2 && user.FirstName != "" {
userStr = fmt.Sprintf("[%s](tg://user?id=%d)", user.FirstName, user.ID)
return userStr
} else if len(userStr) < 2 {
userStr = fmt.Sprintf("[%d](tg://user?id=%d)", user.ID, user.ID)
return userStr
} else {
// escape only if user has a username
return str.MarkdownEscape(userStr)
}
return lnbits.User{Telegram: user}.GetUserStrMd()
}
func appendUinqueUsersToSlice(slice []*tb.User, i *tb.User) []*tb.User {
for _, ele := range slice {
if ele.ID == i.ID {
@@ -71,10 +50,12 @@ func (bot *TipBot) GetUserBalanceCached(user *lnbits.User) (amount int64, err er
}
func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
if user.Wallet == nil {
return 0, errors.New("User has no wallet")
}
wallet, err := bot.Client.Info(*user.Wallet)
if err != nil {
errmsg := fmt.Sprintf("[GetUserBalance] Error: Couldn't fetch user %s's info from LNbits: %s", GetUserStr(user.Telegram), err.Error())
log.Errorln(errmsg)
return
}
user.Wallet.Balance = wallet.Balance
@@ -84,7 +65,15 @@ func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
}
// msat to sat
amount = int64(wallet.Balance) / 1000
log.Debugf("[GetUserBalance] %s's balance: %d sat\n", GetUserStr(user.Telegram), amount)
log.WithFields(log.Fields{
"module": "telegram",
"func": "GetUserBalance",
"user": GetUserStr(user.Telegram),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"telegram_id": user.Telegram.ID,
"amount": amount},
).Debugf("updated user balance")
// update user balance in cache
bot.Cache.Set(
@@ -92,7 +81,7 @@ func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
amount,
&store.Options{Expiration: 1 * time.Hour},
)
return
return amount, nil
}
func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, error) {
@@ -105,8 +94,6 @@ func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, e
log.Printf("[CreateWalletForTelegramUser] Creating wallet for user %s ... ", userStr)
err := bot.createWallet(user)
if err != nil {
errmsg := fmt.Sprintf("[CreateWalletForTelegramUser] Error: Could not create wallet for user %s", userStr)
log.Errorln(errmsg)
return user, err
}
// todo: remove this. we're doing this already in bot.createWallet().
@@ -114,7 +101,14 @@ func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, e
if err != nil {
return nil, err
}
log.Printf("[CreateWalletForTelegramUser] Wallet created for user %s. ", userStr)
log.WithFields(log.Fields{
"module": "telegram",
"func": "CreateWalletForTelegramUser",
"user": GetUserStr(user.Telegram),
"user_id": user.ID,
"wallet_id": user.Wallet.ID,
"error": err.Error()},
).Printf("Wallet created")
return user, nil
}
+34 -21
View File
@@ -1,17 +1,20 @@
package main
import (
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/api"
"github.com/LightningTipBot/LightningTipBot/internal/api/admin"
"github.com/LightningTipBot/LightningTipBot/internal/lndhub"
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"net/http"
"runtime/debug"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/api"
"github.com/LightningTipBot/LightningTipBot/internal/api/admin"
"github.com/LightningTipBot/LightningTipBot/internal/api/userpage"
"github.com/LightningTipBot/LightningTipBot/internal/lndhub"
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
_ "net/http/pprof"
tb "gopkg.in/lightningtipbot/telebot.v3"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits/webhook"
"github.com/LightningTipBot/LightningTipBot/internal/price"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
@@ -19,17 +22,8 @@ import (
)
// setLogger will initialize the log format
func setLogger() {
log.SetLevel(log.DebugLevel)
customFormatter := new(log.TextFormatter)
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
customFormatter.FullTimestamp = true
log.SetFormatter(customFormatter)
}
func main() {
// set logger
setLogger()
defer withRecovery()
price.NewPriceWatcher().Start()
@@ -38,28 +32,47 @@ func main() {
bot.Start()
}
func startApiServer(bot *telegram.TipBot) {
// log errors from interceptors
bot.Telegram.OnError = func(err error, ctx tb.Context) {
// we already log in the interceptors
}
// start internal webhook server
webhook.NewServer(bot)
// start external api server
s := api.NewServer(internal.Configuration.Bot.LNURLServerUrl.Host)
// append lnurl handler functions
// append lnurl ctx functions
lnUrl := lnurl.New(bot)
s.AppendRoute("/.well-known/lnurlp/{username}", lnUrl.Handle, http.MethodGet)
s.AppendRoute("/@{username}", lnUrl.Handle, http.MethodGet)
// userpage server
userpage := userpage.New(bot)
s.AppendRoute("/@{username}", userpage.UserPageHandler, http.MethodGet)
s.AppendRoute("/app/@{username}", userpage.UserWebAppHandler, http.MethodGet)
// append lndhub handler functions
// append lndhub ctx functions
hub := lndhub.New(bot)
s.AppendRoute(`/lndhub/ext/{.*}`, hub.Handle)
s.AppendRoute(`/lndhub/ext`, hub.Handle)
s.AppendAuthorizedRoute(`/lndhub/ext/auth`, api.AuthTypeNone, api.AccessKeyTypeNone, bot.DB.Users, hub.Handle)
s.AppendAuthorizedRoute(`/lndhub/ext/{.*}`, api.AuthTypeBearerBase64, api.AccessKeyTypeAdmin, bot.DB.Users, hub.Handle)
s.AppendAuthorizedRoute(`/lndhub/ext`, api.AuthTypeBearerBase64, api.AccessKeyTypeAdmin, bot.DB.Users, hub.Handle)
// starting api service
apiService := api.Service{Bot: bot}
s.AppendAuthorizedRoute(`/api/v1/paymentstatus/{payment_hash}`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.PaymentStatus, http.MethodPost)
s.AppendAuthorizedRoute(`/api/v1/invoicestatus/{payment_hash}`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.InvoiceStatus, http.MethodPost)
s.AppendAuthorizedRoute(`/api/v1/payinvoice`, api.AuthTypeBasic, api.AccessKeyTypeAdmin, bot.DB.Users, apiService.PayInvoice, http.MethodPost)
s.AppendAuthorizedRoute(`/api/v1/invoicestream`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.InvoiceStream, http.MethodGet)
s.AppendAuthorizedRoute(`/api/v1/createinvoice`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.CreateInvoice, http.MethodPost)
s.AppendAuthorizedRoute(`/api/v1/balance`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.Balance, http.MethodGet)
// start internal admin server
adminService := admin.New(bot)
internalAdminServer := api.NewServer("0.0.0.0:6060")
internalAdminServer := api.NewServer(internal.Configuration.Bot.AdminAPIHost)
internalAdminServer.AppendRoute("/mutex", mutex.ServeHTTP)
internalAdminServer.AppendRoute("/mutex/unlock/{id}", mutex.UnlockHTTP)
internalAdminServer.AppendRoute("/admin/ban/{id}", adminService.BanUser)
internalAdminServer.AppendRoute("/admin/unban/{id}", adminService.UnbanUser)
internalAdminServer.AppendRoute("/admin/dalle/enable", adminService.EnableDalle)
internalAdminServer.AppendRoute("/admin/dalle/disable", adminService.DisableDalle)
internalAdminServer.PathPrefix("/debug/pprof/", http.DefaultServeMux)
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 282 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

+22 -6
View File
@@ -118,15 +118,20 @@ advancedMessage = """%s
📖 Du kannst Inline Befehle in jedem Chat verwenden, sogar in privaten Nachrichten. Warte eine Sekunde, nachdem du den Befehl eingegeben hast und *klicke* auf das Ergebnis, statt Enter einzugeben.
⚙️ *Fortgeschrittene Befehle*
*/transactions* 📊 Liste der Transaktionen
*/link* 🔗 Verbinde dein Wallet mit [BlueWallet](https://bluewallet.io/) oder [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Lnurl empfangen oder senden: `/lnurl` or `/lnurl <lnurl>`
*/lnurl* ⚡️ Lnurl empfangen oder senden: `/lnurl` oder `/lnurl <lnurl>`
*/faucet* 🚰 Erzeuge einen Zapfhahn: `/faucet <gesamt> <pro_user>`
*/tipjar* 🍯 Erzeuge eine Spendendose: `/tipjar <gesamt> <pro_user>`"""
*/tipjar* 🍯 Erzeuge eine Spendendose: `/tipjar <gesamt> <pro_user>`
*/group* 🎟 Tickets für Gruppenchats: `/group add <meine_gruppe> [<ticket_preis>]`
*/shop* 🛍 Durchsuche Shops: `/shop` oder `/shop <user/shop_id>`
*/generate* 🎆 Generiere Bilder mit DALLE-2: `/generate <beschreibung>`"""
# GENERIC
enterAmountRangeMessage = """⌨️ Gebe einen Betrag zwischen %d und %d sat ein."""
enterAmountMessage = """⌨️ Gebe einen Betrag ein."""
errorReasonMessage = """🚫 Fehler: %s"""
enterAmountRangeMessage = """💯 Gebe Betrag zwuschen %d und %d sat ein."""
enterAmountMessage = """💯 Gebe Betrag ein."""
enterUserMessage = """👤 Gebe Benutzernamen ein."""
errorReasonMessage = """🚫 Fehler: %s"""
# START
@@ -256,11 +261,22 @@ lnurlWithdrawSuccess = """✅ Abhebung angefordert."""
walletConnectMessage = """🔗 *Verbinde dein Wallet*
⚠️ Teile diese URL und den QR code mit niemandem! Jeder, der darauf Zugriff hat, hat auch Zugriff auf dein Konto.
⚠️ Teile diese URL und den QR code mit niemandem! Jeder, der darauf Zugriff hat, hat auch Zugriff auf dein Konto. Nutze /api für deine API keys.
- *BlueWallet:* Drücke *New wallet*, *Import wallet*, *Scan or import a file*, und scanne den QR Code.
- *Zeus:* Kopiere die URL unten, drücke *Add a new node*, *Import* (die URL), *Save Node Config*."""
couldNotLinkMessage = """🚫 Konnte dein Wallet nicht verbinden. Bitte versuche es später noch einmal."""
linkHiddenMessage = """🔍 Link versteckt. Gebe /link ein um ihn wieder zu sehen."""
# API
walletConnectMessage = """🔗 *Deine API Keys*
⚠️ Teile diese Key mit niemandem! Jeder, der darauf Zugriff hat, hat auch Zugriff auf dein Konto. Nutze /link um dein Wallet zu verbinden.
- *Admin key:* `%s`
- *Invoice key:* `%s`"""
apiHiddenMessage = """🔍 Keys versteckt. Gebe /api ein um sie wieder zu sehen."""
# FAUCET
+59 -4
View File
@@ -121,15 +121,21 @@ advancedMessage = """%s
📖 You can use inline commands in every chat, even in private conversations. Wait a second after entering an inline command and *click* the result, don't press enter.
⚙️ *Advanced commands*
*/transactions* 📊 List transactions
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Lnurl receive or pay: `/lnurl` or `/lnurl <lnurl>`
*/faucet* 🚰 Create a faucet: `/faucet <capacity> <per_user>`
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`"""
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
# GENERIC
enterAmountRangeMessage = """💯 Enter an amount between %d and %d sat."""
enterAmountMessage = """💯 Enter an amount."""
enterUserMessage = """👤 Enter a user."""
enterTextMessage = """⌨️ Enter text."""
errorReasonMessage = """🚫 Error: %s"""
# START
@@ -189,6 +195,7 @@ invoiceHelpText = """📖 Oops, that didn't work. %s
*Usage:* `/invoice <amount> [<memo>]`
*Example:* `/invoice 1000 Thank you!`"""
invoicePaidText = """✅ Invoice paid."""
# PAY
@@ -223,7 +230,7 @@ donateHelpText = """📖 Oops, that didn't work. %s
# PHOTO
photoQrNotRecognizedMessage = """🚫 Could not regocognize a Lightning invoice or an LNURL. Try to center the QR code, crop the photo, or zoom in."""
photoQrNotRecognizedMessage = """🚫 Could not recognize a Lightning invoice or a LNURL. Try to center the QR code, crop the photo, or zoom in."""
photoQrRecognizedMessage = """✅ QR code:
`%s`"""
@@ -260,13 +267,23 @@ lnurlWithdrawSuccess = """✅ Withdrawal requested."""
walletConnectMessage = """🔗 *Link your wallet*
⚠️ Never share the URL or the QR code with anyone or they will be able to access your funds.
⚠️ Never share the URL or the QR code with anyone or they will be able to access your funds. Use /api for your API keys.
- *BlueWallet:* Press *New wallet*, *Import wallet*, *Scan or import a file*, and scan the QR code.
- *Zeus:* Copy the URL below, press *Add a new node*, *Import* (the URL), *Save Node Config*."""
- *Zeus:* Copy the URL below, press *Add a new node*, select *LNDHub* as Node interface, enter the URL, *Save Node Config*."""
couldNotLinkMessage = """🚫 Couldn't link your wallet. Please try again later."""
linkHiddenMessage = """🔍 Link hidden. Enter /link to see it again."""
# API
apiConnectMessage = """🔗 *Your API keys*
⚠️ Never share these keys with anyone or they will be able to access your funds. Use /link to link your wallet.
- *Admin key:* `%s`
- *Invoice key:* `%s`"""
apiHiddenMessage = """🔍 Keys hidden. Enter /api to see them again."""
# FAUCET
inlineQueryFaucetTitle = """🚰 Create a faucet."""
@@ -347,3 +364,41 @@ inlineTipjarHelpText = """📖 Oops, that didn't work. %s
*Usage:* `/tipjar <capacity> <per_user>`
*Example:* `/tipjar 210 21`"""
# GROUP TICKETS
groupAddGroupHelpMessage = """📖 Oops, that didn't work. This command only works in a group chat. Only group owners can use this command.\nUsage: `/group add <group_name> [<amount>]`\nExample: `/group add TheBestBitcoinGroup 1000`"""
groupJoinGroupHelpMessage = """📖 Oops, that didn't work. Please try again.\nUsage: `/join <group_name>`\nExample: `/join TheBestBitcoinGroup`"""
groupClickToJoinMessage = """🎟 [Click here](%s) 👈 to join `%s`."""
groupTicketIssuedGroupMessage = """🎟 User %s has received a ticket for this group."""
groupPayInvoiceMessage = """🎟 To join the group %s, pay the invoice above."""
groupBotIsNotAdminMessage = """🚫 Oops, that didn't work. You must make me admin and grant me rights to invite users."""
groupNameExists = """🚫 A group with this name already exists. Please choose a different name."""
groupAddedMessage = """🎟 Tickets for group `%s` added.\nAlias: `%s` Price: %d sat\n\nTo request a ticket for this group, start a private chat with %s and write `/join %s`."""
groupNotFoundMessage = """🚫 Could not find a group with this name."""
groupReceiveTicketInvoiceCommission = """🎟 You received *%d sat* (excl. %d sat commission) for a ticket for group `%s` paid by user %s."""
groupReceiveTicketInvoice = """🎟 You received *%d sat* for a ticket for group `%s` paid by user %s."""
commandPrivateMessage = """Please use this command in a private chat with %s."""
groupHelpMessage = """🎟 Private group tickets 🎟
Sell tickets for your _private Group_ and get rid of spam bots.
*Instructions for group admins:*
1) Invite %s to your group and make it admin.
2) Make your group private.
3) In your group, you (the group owner) write `/group add <mygroup> [<ticket_price>]`.
_Fees: The bot takes a 10%% +10 sat commission for cheap tickets. If the ticket is >= 1000 sat, the commission is 2%% + 100 sat._
*Instructions for group members:*
To join a group, talk to %s and write in a private message `/join <mygroup>`.
📖 *Usage:*
*For admins (in group chat):* `/group add <group_name> [<ticket_price>]`\nExample: `/group add TheBestBitcoinGroup 1000`
*For users (in private chat):* `/join <group_name>`\nExample: `/join TheBestBitcoinGroup`"""
# DALLE GENERATE
generateDalleHelpMessage = """Generate images using OpenAI DALLE 2.\nUsage: `/generate <prompt>`\nPrice: 1000 sat"""
generateDallePayInvoiceMessage = """Pay this invoice to generate four images 👇"""
generateDalleGeneratingMessage = """Your images are being generated. Please wait..."""
+5 -1
View File
@@ -117,10 +117,14 @@ advancedMessage = """%s
📖 Puedes usar comandos _inline_ en todos los chats, incluso en las conversaciones privadas. Espera un segundo después de introducir un comando _inline_ y *haz clic* en el resultado, no pulses enter.
⚙️ *Comandos avanzados*
*/transactions* 📊 List transactions
*/link* 🔗 Enlaza tu monedero a [ BlueWallet ](https://bluewallet.io/) o [ Zeus ](https://zeusln.app/)
*/lnurl* ⚡️ Lnurl recibir o pagar: `/lnurl` o `/lnurl <lnurl>`
*/faucet* 🚰 Crear un grifo: `/faucet <capacidad> <por_usuario>`
*/tipjar* 🍯 Crear un tipjar: `/tipjar <capacidad> <por_usuario>`"""
*/tipjar* 🍯 Crear un tipjar: `/tipjar <capacidad> <por_usuario>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
# GENERIC
enterAmountRangeMessage = """💯 Introduce un monto entre %d y %d sat."""
+5 -1
View File
@@ -117,10 +117,14 @@ advancedMessage = """%s
📖 Vous pouvez utiliser ces commandes dans tous les chats et même dans les conversations privées. Attendez une seconde après avoir tapé une commandé puis *click* sur le résultat, n'appuyez pas sur entrée.
⚙️ *Commandes avancées*
*/transactions* 📊 List transactions
*/link* 🔗 Lier votre wallet à [BlueWallet](https://bluewallet.io/) ou [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Lnurl recevoir ou payer: `/lnurl` ou `/lnurl <lnurl>`
*/faucet* 🚰 Créer un faucet: `/faucet <capacité> <par_utilisateur>`
*/tipjar* 🍯 Créer un tipjar: `/tipjar <capacité> <par_utilisateur>`"""
*/tipjar* 🍯 Créer un tipjar: `/tipjar <capacité> <par_utilisateur>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
# GENERIC
enterAmountRangeMessage = """💯 Choisissez un montant entre %d et %d sat."""
+5 -1
View File
@@ -117,10 +117,14 @@ advancedMessage = """%s
📖 Kamu dapat menggunakan sebaris perintah di tiap percakapan, bahkan di percakapan privat. Tunggu sejenak setelah memasukkan sebaris perintah lalu *pencet* hasilnya, jangan tekan enter.
⚙️ *Perintah lanjutan*
*/transactions* 📊 List transactions
*/link* 🔗 Menghubungkan dompet mu ke [BlueWallet](https://bluewallet.io/) atau [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Lnurl menerima atau membayar: `/lnurl` atau `/lnurl <lnurl>`
*/faucet* 🚰 Membuat sebuah keran `/faucet <kapasitas> <per_pengguna>`
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`"""
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
# GENERIC
enterAmountRangeMessage = """💯 Masukkan jumlah diantara %d dan %d sat."""
+5 -1
View File
@@ -117,10 +117,14 @@ advancedMessage = """%s
📖 Puoi usare i comandi in linea in ogni chat, anche nelle conversazioni private. Attendi un secondo dopo aver inviato un comando in linea e *clicca* sull'azione desiderata, non premere invio.
⚙️ *Comandi avanzati*
*/transactions* 📊 List transactions
*/link* 🔗 Crea un collegamento al tuo wallet [BlueWallet](https://bluewallet.io/) o [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Ricevi o paga un Lnurl: `/lnurl` or `/lnurl <lnurl>`
*/faucet* 🚰 Crea una distribuzione: `/faucet <totale> <per_utente>`
*/tipjar* 🍯 Crea un tipjar: `/tipjar <totale> <per_utente>`"""
*/tipjar* 🍯 Crea un tipjar: `/tipjar <totale> <per_utente>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
# GENERIC
enterAmountRangeMessage = """💯 Imposta un ammontare tra %d e %d sat."""
+5 -1
View File
@@ -117,10 +117,14 @@ advancedMessage = """%s
📖 Je kunt inline commando's in elke chat gebruiken, zelfs in privé gesprekken. Wacht een seconde na het invoeren van een inline commando en *klik* op het resultaat, druk niet op enter.
⚙️ *Geavanceerde opdrachten*
*/transactions* 📊 List transactions
*/link* 🔗 Koppel uw wallet aan [BlueWallet](https://bluewallet.io/) of [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Lnurl ontvangen of betalen: `/lnurl` of `/lnurl <lnurl>`
*/faucet* 🚰 Maak een kraan: `/faucet <capacity> <per_user>`
*/tipjar* 🍯 Maak een tipjar: `/tipjar <capacity> <per_user>`"""
*/tipjar* 🍯 Maak een tipjar: `/tipjar <capacity> <per_user>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
# GENERIC
enterAmountRangeMessage = """💯 Voer een bedrag in tussen %d en %d sat."""
+4 -1
View File
@@ -117,10 +117,13 @@ advancedMessage = """%s
📖 Você pode usar comandos _inline_ em todas as conversas, mesmo em conversas privadas. Espere um segundo após inserir um comando _inline_ e *clique* no resultado, não pressione enter.
⚙️ *Comandos avançados*
*/transactions* 📊 List transactions
*/link* 🔗 Vincule sua carteira a [ BlueWallet ](https://bluewallet.io/) ou [ Zeus ](https://zeusln.app/)
*/lnurl* ⚡️ Receber ou pagar com lnurl: `/lnurl` o `/lnurl <lnurl>`
*/faucet* 🚰 Criar uma torneira: `/faucet <capacidade> <por_usuário>`
*/tipjar* 🍯 Criar uma tipjar: `/tipjar <capacidade> <por_usuário>`"""
*/tipjar* 🍯 Criar uma tipjar: `/tipjar <capacidade> <por_usuário>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
# GENERIC
enterAmountRangeMessage = """💯 Insira uma quantia entre %d e %d sat."""
+4 -1
View File
@@ -121,10 +121,13 @@ advancedMessage = """%s
📖 Вы можете использовать команды в любом чате, даже в личных беседах. Подождите секунду после ввода команды и *щелкните* результат, не нажимайте Enter..
⚙️ *Продвинутые команды*
*/transactions* 📊 List transactions
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
*/lnurl* Получить или оплатить через ⚡️Lnurl: `/lnurl` or `/lnurl <lnurl>`
*/faucet* 🚰 Создать криптораздачу: `/faucet <ёмкость> <на_пользователя>`
*/tipjar* 🍯 Создать копилку: `/tipjar <ёмкость> <на_пользователя>`"""
*/tipjar* 🍯 Создать копилку: `/tipjar <ёмкость> <на_пользователя>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
# GENERIC
enterAmountRangeMessage = """💯 Введите количество между %d и %d sat."""
+4 -1
View File
@@ -117,10 +117,13 @@ advancedMessage = """%s
📖 İnline komutları her sohbette ve hatta özel mesajlarda kullanabilirsin. Komutu yazdıktan sonra bir saniye bekle ve Enter yazmak yerine sonuca *tıkla*.
⚙️ *Gelişmiş komutlar*
*/transactions* 📊 List transactions
*/link* 🔗 Cüzdanını bağla: [BlueWallet](https://bluewallet.io/) veya [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Lnurl iste veya gönder: `/lnurl` veya `/lnurl <lnurl>`
*/faucet* 🚰 Bir fıçı oluştur: `/faucet <toplam> <kullanıcı_başına>`
*/tipjar* 🍯 Bir tipjar oluştur: `/tipjar <capacity> <per_user>`"""
*/tipjar* 🍯 Bir tipjar oluştur: `/tipjar <capacity> <per_user>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
# GENERIC
enterAmountRangeMessage = """💯 %d ve %d sat arasında bir miktar gir."""