Compare commits

..
228 Commits
Author SHA1 Message Date
callebtcandGitHub 7c55e40966 Add setting file (#497)
* add user currency for incoming payments

* also add currency to incoming LNURL payments

* add setting file
2023-12-05 16:02:42 +01:00
callebtcandGitHub 5adf090969 Display fiat currency (#496)
* add user currency for incoming payments

* also add currency to incoming LNURL payments
2023-12-05 15:54:53 +01:00
callebtcandGitHub 0be3d26e56 do not store lnurl comments below amount threshold (#493) 2023-11-23 11:59:35 -03:00
callebtcandGitHub 8b2fb73fe8 allow lnurlp comments only for 21 sats or more (#491) 2023-11-15 21:36:37 -03:00
callebtcandGitHub 7ba59512de lnurlp: filter links for small payments (#490) 2023-11-15 21:31:56 -03:00
callebtcandGitHub 432da6da71 disable preview in lnurl comments (#488) 2023-11-14 11:02:31 -03:00
callebtcandGitHub 532dbfe23b show error on wrong send message (#487) 2023-10-31 21:15:44 -03:00
gohumbleandGitHub d88b04afb9 update inputmode to decimal (ios keyboard) (#416) 2023-08-13 15:17:50 +02:00
Massimo MusumeciandGitHub c4f6d31779 Fix in config example file (#472)
* added massmux full install guide

* config example file fix
2023-08-13 15:17:32 +02:00
callebtcandGitHub 991954493b add amountsMap (#483) 2023-08-13 15:12:56 +02:00
307780200a add logs (#479)
* added docker dockerfile and compose including lnd + bitcoind + c-lightning + lnbits

* Revert "added docker dockerfile and compose including lnd + bitcoind + c-lightning + lnbits"

This reverts commit 69e66450a3e6b5d3296280675c51ac54ded09d01.

* update CommentAllowed

* update donate

* fix amount

* Update database.go

---------

Co-authored-by: gohumble <humble@gmail.com>
2023-06-29 14:44:56 +02:00
gohumbleandGitHub 6a9c5f4a8a fix amount (#478)
* added docker dockerfile and compose including lnd + bitcoind + c-lightning + lnbits

* Revert "added docker dockerfile and compose including lnd + bitcoind + c-lightning + lnbits"

This reverts commit 69e66450a3e6b5d3296280675c51ac54ded09d01.

* update CommentAllowed

* update donate

* fix amount
2023-06-29 13:40:45 +02:00
gohumbleandGitHub 8e9c03d0e5 update CommentAllowed and donate
* update CommentAllowed

* update donate
2023-06-29 13:28:41 +02:00
calleandGitHub 84951d525c max relays (#476) 2023-03-25 02:55:47 +01:00
calleandGitHub 6e6fb5d183 feedback (#474) 2023-02-28 14:11:50 +01:00
calleandGitHub a65bf8d6f7 nostr: respond on empty command for new users (#473) 2023-02-28 13:55:26 +01:00
tlindiandGitHub aeb0c4a728 Create fi.toml Translate-Finnish (#469)
* Create fi.toml Translate-Finnish

* Update localize.go
2023-02-24 19:45:24 +01:00
calleandGitHub 722c9c3c83 add /zap command for /tip (#468) 2023-02-23 23:06:34 +01:00
Massimo MusumeciandGitHub b4310b0efd added massmux full install guide (#467) 2023-02-23 10:03:55 +01:00
calleandGitHub 1090b38b73 zaps: remove necessity to add pubkey (#465) 2023-02-21 15:43:07 +01:00
calleandGitHub 4fb4f54b5d Nostr/brrrr (#463)
* readd brr

* readd brrrrr
2023-02-18 16:36:05 +01:00
calleandGitHub ba256a1452 nostr logging and new relays (#462) 2023-02-18 15:59:36 +01:00
calleandGitHub 4769764c98 Merge pull request #461 from LightningTipBot/nostr/fix_nip057_pubkey
nostr: add bot pubkey to LNURLFirst not users
2023-02-17 14:51:48 +01:00
callebtc ed17953a82 nostr: add bot pubkey to LNURLFirst not users 2023-02-17 14:51:08 +01:00
calleandGitHub 7f0c6356c3 Merge pull request #459 from LightningTipBot/nostr/nip05_add_files
add files
2023-02-16 21:20:32 +01:00
callebtc 91cbf83733 add files 2023-02-16 21:20:08 +01:00
calleandGitHub e7d1f9e7c3 add nip05 (#458) 2023-02-16 20:51:22 +01:00
calleandGitHub cc4cb1cb01 Merge pull request #457 from LightningTipBot/nostr/relay_time
clean url and wait for connect
2023-02-16 19:00:52 +01:00
callebtc bdaf46c78b clean url and wait for connect 2023-02-16 19:00:29 +01:00
calleandGitHub 4c3cb071f2 Merge pull request #456 from LightningTipBot/nostr/e_tag_optional
nostr: optional e
2023-02-16 17:00:50 +01:00
callebtc 3a6771934b nostr: optional e 2023-02-16 17:00:20 +01:00
calleandGitHub 63cbd57bc9 Merge pull request #455 from LightningTipBot/nostr/moar_relays
moar relays
2023-02-16 16:08:53 +01:00
callebtc a712f52a15 moar relays 2023-02-16 16:07:14 +01:00
calleandGitHub 603dbaa6a5 Merge pull request #454 from LightningTipBot/nostr/logging
log nostr event id
2023-02-16 13:14:39 +01:00
callebtc 1a2776ab24 log nostr event id 2023-02-16 13:13:08 +01:00
calleandGitHub b9cddbeedd Merge pull request #453 from LightningTipBot/nostr/nip57-fix-parser
fix nostr parser
2023-02-16 12:59:58 +01:00
callebtc 40e7fcaa5c fix nostr parser 2023-02-16 12:58:59 +01:00
calleandGitHub c8ef698a88 Merge pull request #452 from LightningTipBot/nostr/add_files
Nostr: add files
2023-02-16 12:33:37 +01:00
callebtc 7ab3d4627a add files 2023-02-16 12:33:19 +01:00
calleandGitHub a157521c1a Merge pull request #451 from LightningTipBot/zaps
nip57 zaps
2023-02-16 12:31:49 +01:00
callebtc 4318b48c3c nip57 zaps 2023-02-16 12:29:17 +01:00
calleandGitHub 01a8e3bd91 Merge pull request #449 from LightningTipBot/fix/api_memo
fix: memo in api
2023-02-06 12:41:36 +01:00
callebtc 8dabb381ab fix: memo in api 2023-02-06 12:41:14 +01:00
calleandGitHub 681bf390b3 Merge pull request #447 from LightningTipBot/fix/group_help
group help
2023-01-22 10:29:28 +01:00
callebtc 51f2812ac6 group help 2023-01-22 10:29:06 +01:00
calleandGitHub 6d0bc87f15 Merge pull request #446 from LightningTipBot/kick
group join ticket
2023-01-22 10:26:52 +01:00
callebtc b3bbe614ff fix strings 2023-01-22 10:26:24 +01:00
gohumble 3ea9ef0684 fix text 2023-01-20 21:10:10 +01:00
gohumble 97226991ac fix webhook 2023-01-20 20:44:19 +01:00
gohumble 0225a5998a added tryLoadUserInterceptor 2023-01-20 20:41:46 +01:00
callebtc 56318b3d0b fixes 2023-01-20 17:24:24 +01:00
gohumble ab5da78e39 commission 2023-01-19 16:27:11 +01:00
gohumble 9271668e94 cleanup 2023-01-19 15:55:53 +01:00
gohumble 7eaef102dd rename 2023-01-19 14:44:10 +01:00
gohumble ab00715f51 reset 2023-01-19 14:25:20 +01:00
gohumble 7204d85837 kick ticket initial commit 2023-01-19 14:22:45 +01:00
calleandGitHub 84fe1d7cc2 Merge pull request #445 from LightningTipBot/disable_gpt
disable gpt and remove from help
2023-01-17 00:45:02 +01:00
callebtc 0efc5c4e43 disable gpt and remove from help 2023-01-17 00:44:15 +01:00
calleandGitHub 9e64dbb2fd Merge pull request #444 from LightningTipBot/fix/remove_send_button_temp
remove send button until fixed
2023-01-16 23:30:33 +01:00
callebtc 058278046f remove send button until fixed 2023-01-16 23:30:10 +01:00
calleandGitHub 998967c81e Merge pull request #442 from LightningTipBot/lnurl/advanced_help
add memo to lnurl command
2023-01-14 19:02:13 +01:00
callebtc 1a21a1519f add memo to lnurl command 2023-01-14 19:01:56 +01:00
calleandGitHub c47038fa1c Merge pull request #441 from LightningTipBot/fix/nil_successaction
nil check for successaction context
2023-01-14 18:33:19 +01:00
callebtc 2c76764421 nil check for successaction context 2023-01-14 18:32:49 +01:00
calleandGitHub b0e43f17f0 Merge pull request #440 from LightningTipBot:fix/lnurlp/successaction-url-no-preview
no preview for urls
2023-01-14 18:27:48 +01:00
callebtc 120d7c4419 no preview for urls 2023-01-14 18:27:30 +01:00
calleandGitHub 73d87fc4bb Merge pull request #439 from LightningTipBot/lnurl/successAction
add successaction
2023-01-14 18:23:13 +01:00
callebtc 2f61a96e87 add successaction 2023-01-14 18:21:53 +01:00
calleandGitHub 3112b79c0d Merge pull request #437 from LightningTipBot/shop/remove_limit
shop: remove limit
2022-12-25 13:30:02 +01:00
callebtc b50270fe0a remove limit 2022-12-25 13:29:25 +01:00
gohumbleandGitHub 8598adb280 added chatGPT (#435) 2022-12-11 19:12:34 +01:00
calleandGitHub 74e9f7aabf Merge pull request #434 from LightningTipBot/translation/fr/fix_lnurl
fix: fr translation lnurl message
2022-12-08 14:38:36 +01:00
callebtc 8b32e5fda5 fix: fr translation lnurl message 2022-12-08 14:37:41 +01:00
gohumbleandGitHub d264650207 #432 return default http client for empty socks host configuration (#433) 2022-11-28 19:33:02 +01:00
gohumbleandGitHub c611969feb moved translation (#431) 2022-11-03 10:15:48 +01:00
sifrantandGitHub 01f4cff348 Translation cz (#425) 2022-11-03 10:04:58 +01:00
gohumbleandGitHub a67ec62054 added isOnionRegex (#430) 2022-11-03 09:32:38 +01:00
gohumbleandGitHub 895fd06a14 added GetClientForScheme (#429) 2022-11-03 09:20:32 +01:00
ChuckNorrisonandGitHub ed5ceeb095 typo in example config (#426)
fix example config filename in installation instructions
2022-10-27 20:02:52 +02:00
gohumbleandGitHub bc8c8f952a trim whitespaces in send handler (#424) 2022-10-20 09:36:59 +02:00
gohumbleandGitHub 64055db1a5 sse fix (#422)
* fix sse

* close c
2022-10-06 14:18:29 +02:00
gohumbleandGitHub ec679d5e6b removed connection keep alive header (#421) 2022-10-06 09:48:23 +02:00
gohumbleandGitHub 9e8958ece2 Update pl.toml (#419)
fix polish help text from #417
2022-09-25 20:48:27 +02:00
7a2aba59ff add polish (#417)
* add polish

* Update localize.go

LoadMessageFile

Co-authored-by: Maciej Sołtysiak <maciej@soltysiak.com>
Co-authored-by: gohumble <55599638+gohumble@users.noreply.github.com>
2022-09-25 20:25:27 +02:00
calleandGitHub 62d7dd965e Merge pull request #418 from LightningTipBot/fix/api_user_lookup
fix api lookup
2022-09-18 00:41:56 +03:00
callebtc 32a5863b25 fix api lookup 2022-09-18 00:41:14 +03:00
gohumbleandGitHub 45931c087a decode lnurl using strict functions (#415) 2022-09-07 18:47:52 +02:00
gohumbleandGitHub c561ae24d3 updated golnurl (#414) 2022-09-07 18:12:25 +02:00
calleandGitHub d5ff4867c0 Merge pull request #413 from LightningTipBot/dalle_logging_update
krass
2022-08-31 22:42:51 +02:00
callebtc 1f5a6a5a31 krass 2022-08-31 22:42:19 +02:00
calleandGitHub e8f24d99ee Merge pull request #412 from LightningTipBot/buttonfix123
button fix
2022-08-31 22:38:16 +02:00
callebtc b9bf071de9 button fix 2022-08-31 22:36:16 +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
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
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
callebtc 0ff0d889ff sse 2022-08-20 22:33:05 +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
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
79 changed files with 5343 additions and 470 deletions
+7 -3
View File
@@ -18,7 +18,7 @@ To build the bot from source, clone the repository and compile the source code.
git clone https://github.com/LightningTipBot/LightningTipBot.git
cd LightningTipBot
go build .
cp config.yaml-example config.yaml
cp config.yaml.example config.yaml
```
After the configuration (see below), start it using the command
@@ -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).
@@ -136,6 +136,10 @@ To pay a Lightning invoice, you can snap a photo of a QR code and send it direct
To minimize the clutter all the heavy tipping can cause in a group chat, the bot will remove all failed commands (for example due to a syntax error) from the chat immediately. All successful commands will stay visible for `message_dispose_duration` seconds (default 10s) and then be removed. The tips will sill be visible for everyone in the Live tooltip. This feature only works, if the bot is made admin of the group.
## Full Guide to Install and run on a VPS
A complete guide to install and run LightningTipBot + LNBITS (on docker with PostgreSQL) on the same VPS with an external LND funding source has been prepared by Massimo Musumeci (@massmux) and it is available: [LightningTipBot full install](https://www.massmux.com/howto-complete-lightningtipbot-lnbits-setup-vps/)
## Made with
- [LNbits](https://github.com/lnbits/lnbits) – Free and open-source lightning-network wallet/accounts system.
+10 -2
View File
@@ -6,9 +6,10 @@ bot:
tor_proxy:
host: 127.0.0.1:9050
http_proxy: ""
lnurl_public_host_name: "mylnurl.com"
lnurl_server: "https://mylnurl.com"
lnurl_public_host_name: "https://mylnurl.com"
lnurl_server: "http://127.0.0.1:5454" # or http://0.0.0.0:5454 depending on your configuration
lnurl_image: true
admin_api_host: localhost:6060
telegram:
message_dispose_duration: 10
api_key: "1234"
@@ -24,3 +25,10 @@ database:
transactions_path: "data/transactions.db"
shop_buntdb_path: "data/shop.db"
groupsdb_path: "data/groups.db"
generate:
open_ai_bearer_token: "token_here"
dalle_key: "asd"
dalle_price: 1000
worker: 2
nostr:
private_key: "hex private key here"
+1
View File
@@ -0,0 +1 @@
this is where dalle images are stored
+53 -30
View File
@@ -1,85 +1,108 @@
module github.com/LightningTipBot/LightningTipBot
go 1.17
go 1.18
require (
github.com/BurntSushi/toml v0.3.1
github.com/PuerkitoBio/goquery v1.8.0
github.com/btcsuite/btcd v0.20.1-beta.0.20200515232429-9f0179fd2c46
github.com/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.3-0.20220819192234-5c5819dd0aa7
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/nbd-wtf/go-nostr v0.13.0
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/sirupsen/logrus v1.6.0
github.com/prometheus/common v0.26.0
github.com/r3labs/sse v0.0.0-20210224172625-26fe804710bc
github.com/satori/go.uuid v1.2.0
github.com/sirupsen/logrus v1.7.0
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
github.com/tidwall/buntdb v1.2.7
github.com/tidwall/gjson v1.12.1
github.com/tidwall/sjson v1.2.4
golang.org/x/net v0.0.0-20210916014120-12bc252f5db8
golang.org/x/text v0.3.6
golang.org/x/time v0.0.0-20191024005414-555d28b269f0
gopkg.in/lightningtipbot/telebot.v3 v3.0.0-20220326213923-f323bb71ac8e
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
gorm.io/driver/sqlite v1.1.4
gorm.io/gorm v1.21.12
)
require (
github.com/SaveTheRbtz/generic-sync-map-go v0.0.0-20220414055132-a37292614db8 // indirect
github.com/XiaoMi/pegasus-go-client v0.0.0-20210427083443-f3b6b08bc4c2 // indirect
github.com/aead/siphash v1.0.1 // indirect
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d // 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/btcutil v1.0.2 // indirect
github.com/btcsuite/btcwallet v0.11.1-0.20200515224913-e0e62245ecbe // indirect
github.com/btcsuite/btcwallet/wallet/txauthor v1.0.0 // indirect
github.com/btcsuite/btcwallet/wallet/txrules v1.0.0 // indirect
github.com/btcsuite/btcwallet/wallet/txsizes v1.0.0 // indirect
github.com/btcsuite/btcwallet/walletdb v1.3.1 // indirect
github.com/btcsuite/btcwallet/wtxmgr v1.1.1-0.20200515224913-e0e62245ecbe // 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/gorilla/websocket v1.4.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.2 // indirect
github.com/kkdai/bstream v0.0.0-20181106074824-b3251f7901ec // indirect
github.com/konsorten/go-windows-terminal-sequences v1.0.3 // indirect
github.com/kkdai/bstream v1.0.0 // indirect
github.com/lightninglabs/gozmq v0.0.0-20191113021534-d20a764486bf // indirect
github.com/lightninglabs/neutrino v0.11.1-0.20200316235139-bffc52e8f200 // indirect
github.com/lightningnetwork/lnd v0.10.1-beta // indirect
github.com/lightningnetwork/lnd/queue v1.0.3 // indirect
github.com/lightningnetwork/lnd/ticker v1.0.0 // 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/mattn/go-sqlite3 v1.14.5 // indirect
github.com/miekg/dns v1.0.14 // 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.3.1 // 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.19.0 // indirect
go.opentelemetry.io/otel/metric v0.19.0 // indirect
go.opentelemetry.io/otel/trace v0.19.0 // indirect
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 // indirect
github.com/valyala/fastjson v1.6.3 // 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/exp v0.0.0-20221106115401-f9659909a136 // indirect
golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde // indirect
golang.org/x/sys v0.1.0 // indirect
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
gopkg.in/alecthomas/kingpin.v2 v2.2.6 // indirect
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 // indirect
gopkg.in/yaml.v2 v2.3.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
k8s.io/apimachinery v0.0.0-20191123233150-4c4803ed55e3 // indirect
)
// replace gopkg.in/lightningtipbot/telebot.v2 => ../telebot
// replace gopkg.in/lightningtipbot/telebot.v3 => ../telebot
+742 -41
View File
File diff suppressed because it is too large Load Diff
+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"`
}
+188
View File
@@ -0,0 +1,188 @@
package api
import (
"encoding/json"
"fmt"
"net/http"
"time"
"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)
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,
}
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,
Memo: createInvoiceRequest.Memo,
Webhook: internal.Configuration.Lnbits.WebhookServer},
s.Bot.Client)
if err != nil {
RespondError(w, "could not create invoice")
return
}
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
}
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
}
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
}
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())
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}
client := sse.NewClient(fmt.Sprintf("%s/api/v1/payments/sse", internal.Configuration.Lnbits.Url))
client.Connection.Transport = &http.Transport{DisableCompression: true}
client.Headers = map[string]string{"X-Api-Key": user.Wallet.Inkey}
c := make(chan *sse.Event)
err := client.SubscribeChan("", c)
if err != nil {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}
out:
for {
select {
case msg := <-c:
select {
case <-r.Context().Done():
client.Unsubscribe(c)
break out
default:
written, err := fmt.Fprintf(w, "event: %s\n", string(msg.Event))
if err != nil || written == 0 {
break out
}
written, err = fmt.Fprintf(w, "data: %s\n", string(msg.Data))
if err != nil || written == 0 {
break out
}
written, err = fmt.Fprint(w, "\n")
if err != nil || written == 0 {
break out
}
flusher.Flush()
}
}
}
close(c)
time.Sleep(time.Second * 5)
}
+102
View File
@@ -1,8 +1,16 @@
package api
import (
"context"
"encoding/base64"
"fmt"
"net/http"
"net/http/httputil"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"gorm.io/gorm"
log "github.com/sirupsen/logrus"
)
@@ -16,6 +24,100 @@ func LoggingMiddleware(prefix string, next http.HandlerFunc) http.HandlerFunc {
}
}
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.Warn("[api] 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.Warnf("[api] 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{}
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 = ? OR wallet_adminkey = ? COLLATE NOCASE", password, password).First(user)
} else {
log.Errorf("[api] route without access type")
w.WriteHeader(401)
return
}
if tx.Error != nil {
log.Warnf("[api] could not load access key: %v", tx.Error)
w.WriteHeader(401)
return
}
log.Debugf("[api] User: %s Endpoint: %s %s %s", telegram.GetUserStr(user.Telegram), r.Method, r.URL.Path, r.URL.RawQuery)
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 {
+11 -3
View File
@@ -5,6 +5,8 @@ import (
"net/http"
"time"
"gorm.io/gorm"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
@@ -23,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,
@@ -32,7 +34,7 @@ func NewServer(address string) *Server {
apiServer.router = mux.NewRouter()
apiServer.httpServer.Handler = apiServer.router
go apiServer.httpServer.ListenAndServe()
log.Infof("[API] Server started at %s", address)
log.Infof("[api] Server started at %s", address)
return apiServer
}
@@ -42,6 +44,12 @@ 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("API", 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))
if len(methods) > 0 {
+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="decimal" step="any" pattern="\d+(\.\d*)?" 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}}
+23 -3
View File
@@ -31,7 +31,8 @@ const botImage = "https://avatars.githubusercontent.com/u/88730856?v=7"
//go:embed static
var templates embed.FS
var tmpl = template.Must(template.ParseFS(templates, "static/userpage.html"))
var 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,
@@ -67,7 +68,7 @@ func (s Service) getTelegramUserPictureURL(username string) (string, error) {
}
func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
// https://ln.tips/.well-known/lnurlp/<username>
// 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.Infof("[UserPage] rendering page of %s", username)
@@ -82,7 +83,7 @@ func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
image = botImage
}
if err := tmpl.ExecuteTemplate(w, "userpage", struct {
if err := userpage_tmpl.ExecuteTemplate(w, "userpage", struct {
Username string
Image string
LNURLPay string
@@ -90,3 +91,22 @@ func (s Service) UserPageHandler(w http.ResponseWriter, r *http.Request) {
log.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")
}
}
+14
View File
@@ -14,8 +14,21 @@ var Configuration = struct {
Telegram TelegramConfiguration `yaml:"telegram"`
Database DatabaseConfiguration `yaml:"database"`
Lnbits LnbitsConfiguration `yaml:"lnbits"`
Generate GenerateConfiguration `yaml:"generate"`
Nostr NostrConfiguration `yaml:"nostr"`
}{}
type NostrConfiguration struct {
PrivateKey string `yaml:"private_key"`
}
type GenerateConfiguration struct {
OpenAiBearerToken string `yaml:"open_ai_bearer_token"`
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"`
@@ -30,6 +43,7 @@ type BotConfiguration struct {
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 {
+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)
}
+42
View File
@@ -0,0 +1,42 @@
package database
import (
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"gorm.io/gorm"
)
func FindUser(database *gorm.DB, username string) (*lnbits.User, *gorm.DB) {
// now check for the user
user := &lnbits.User{}
// check if "username" is actually the user ID
tx := database
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
// asume it's anon_id
tx = database.Where("anon_id = ?", username).First(user)
} else if strings.HasPrefix(username, "0x") {
// asume it's anon_id_sha256
tx = database.Where("anon_id_sha256 = ?", username).First(user)
} else if strings.HasPrefix(username, "1x") {
// asume it's uuid
tx = database.Where("uuid = ?", username).First(user)
} else {
// assume it's a string @username
tx = database.Where("telegram_username = ? COLLATE NOCASE", username).First(user)
}
return user, tx
}
func FindUserSettings(user *lnbits.User, settingsTx *gorm.DB) (*lnbits.User, error) {
// tx := bot.DB.Users.Preload("Settings").First(user)
tx := settingsTx.First(user)
if tx.Error != nil {
return user, tx.Error
}
if user.Settings == nil {
user.Settings = &lnbits.Settings{ID: user.ID}
}
return user, nil
}
+102
View File
@@ -0,0 +1,102 @@
package gpt
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"net/http"
)
type Response struct {
Message struct {
ID string `json:"id"`
Role string `json:"role"`
User interface{} `json:"user"`
CreateTime interface{} `json:"create_time"`
UpdateTime interface{} `json:"update_time"`
Content struct {
ContentType string `json:"content_type"`
Parts []string `json:"parts"`
} `json:"content"`
EndTurn interface{} `json:"end_turn"`
Weight float64 `json:"weight"`
Metadata struct {
} `json:"metadata"`
Recipient string `json:"recipient"`
} `json:"message"`
ConversationID string `json:"conversation_id"`
Error interface{} `json:"error"`
}
type Request struct {
Action string `json:"action"`
ConversationId string `json:"conversation_id,omitempty"`
Messages []Messages `json:"messages"`
ParentMessageID string `json:"parent_message_id"`
Model string `json:"model"`
}
type Content struct {
ContentType string `json:"content_type"`
Parts []string `json:"parts"`
}
type Messages struct {
ID string `json:"id"`
Role string `json:"role"`
Content Content `json:"content"`
}
var dataPrefix = []byte("data: ")
var doneSequence = []byte("[DONE]")
func GetRawCompletion(ctx intercept.Context, rr Request, cb func(s string)) (*Response, error) {
rawClient := http.Client{}
r, err := json.Marshal(rr)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx.Context, "POST", "https://chat.openai.com/backend-api/conversation", bytes.NewBuffer(r))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", internal.Configuration.Generate.OpenAiBearerToken))
req.Header.Set("accept", "text/event-stream")
req.Header.Set("authority", "chat.openai.com")
req.Header.Set("accept-language", "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7")
req.Header.Set("Content-type", "application/json")
req.Header.Set("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36")
resp, err := rawClient.Do(req)
if err != nil {
return nil, err
}
reader := bufio.NewReader(resp.Body)
defer resp.Body.Close()
output := new(Response)
for {
line, err := reader.ReadBytes('\n')
if err != nil {
return nil, err
}
// make sure there isn't any extra whitespace before or after
line = bytes.TrimSpace(line)
// the completion API only returns data events
if !bytes.HasPrefix(line, dataPrefix) {
continue
}
line = bytes.TrimPrefix(line, dataPrefix)
// the stream is completed when terminated by [DONE]
if bytes.HasPrefix(line, doneSequence) {
break
}
if err := json.Unmarshal(line, output); err != nil {
return nil, fmt.Errorf("invalid json stream data: %v", err)
}
if len(output.Message.Content.Parts) > 0 {
cb(output.Message.Content.Parts[len(output.Message.Content.Parts)-1])
}
}
return output, nil
}
+3
View File
@@ -18,12 +18,15 @@ func RegisterLanguages() *i18n.Bundle {
bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
bundle.MustLoadMessageFile("translations/en.toml")
bundle.LoadMessageFile("translations/de.toml")
bundle.LoadMessageFile("translations/fi.toml")
bundle.LoadMessageFile("translations/it.toml")
bundle.LoadMessageFile("translations/es.toml")
bundle.LoadMessageFile("translations/nl.toml")
bundle.LoadMessageFile("translations/pl.toml")
bundle.LoadMessageFile("translations/fr.toml")
bundle.LoadMessageFile("translations/pt-br.toml")
bundle.LoadMessageFile("translations/tr.toml")
bundle.LoadMessageFile("translations/cs.toml")
bundle.LoadMessageFile("translations/id.toml")
bundle.LoadMessageFile("translations/ru.toml")
return bundle
+28 -3
View File
@@ -1,6 +1,7 @@
package lnbits
import (
"fmt"
"time"
"github.com/imroc/req"
@@ -84,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",
@@ -131,7 +132,7 @@ func (c Client) Info(w Wallet) (wtx Wallet, err error) {
return
}
// Info returns wallet payments
// Payments returns wallet payments
func (c Client) Payments(w Wallet) (wtx Payments, err error) {
// custom header with invoice key
invoiceHeader := req.Header{
@@ -155,6 +156,30 @@ func (c Client) Payments(w Wallet) (wtx Payments, err error) {
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)
@@ -174,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",
+32 -13
View File
@@ -7,7 +7,8 @@ import (
"time"
"github.com/LightningTipBot/LightningTipBot/internal/satdress"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/imroc/req"
tb "gopkg.in/lightningtipbot/telebot.v3"
@@ -38,10 +39,18 @@ type User struct {
}
type Settings struct {
ID string `json:"id" gorm:"primarykey"`
Node NodeSettings `gorm:"embedded;embeddedPrefix:node_"`
ID string `json:"id" gorm:"primarykey"`
Display DisplaySettings `gorm:"embedded;embeddedPrefix:display_"`
Node NodeSettings `gorm:"embedded;embeddedPrefix:node_"`
Nostr NostrSettings `gorm:"embedded;embeddedPrefix:nostr_"`
}
type DisplaySettings struct {
DisplayCurrency string `json:"displaycurrency"`
}
type NostrSettings struct {
PubKey string `json:"pubkey"`
}
type NodeSettings struct {
NodeType string `json:"nodetype"`
LNDParams *satdress.LNDParams `gorm:"embedded;embeddedPrefix:lndparams_"`
@@ -64,6 +73,7 @@ const (
UserStateShopItemSendPrice
UserStateShopItemSendItemFile
UserEnterShopsDescription
UserEnterDallePrompt
)
type UserStateKey int
@@ -74,11 +84,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 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.
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 {
@@ -116,7 +127,7 @@ type Wallet struct {
User string `json:"user"`
}
type Payments []struct {
type Payment struct {
CheckingID string `json:"checking_id"`
Pending bool `json:"pending"`
Amount int64 `json:"amount"`
@@ -132,17 +143,25 @@ type Payments []struct {
WebhookStatus interface{} `json:"webhook_status"`
}
type BitInvoice struct {
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) {
@@ -154,7 +173,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)
}
+1 -1
View File
@@ -113,7 +113,7 @@ func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
log.Errorln(err)
return
}
c.Function(txInvoiceEvent)
go c.Function(txInvoiceEvent)
return
}
}
-47
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"
)
@@ -21,48 +17,5 @@ func New(bot *telegram.TipBot) LndHub {
return LndHub{database: bot.DB.Users}
}
func (w LndHub) Handle(writer http.ResponseWriter, request *http.Request) {
auth := request.Header.Get("Authorization")
// check if the user is banned
if auth != "" {
_, password, ok := parseBearerAuth(auth)
if !ok {
return
}
// first we make sure that the password is not already "banned_"
if strings.Contains(password, "_") || strings.HasPrefix(password, "banned_") {
log.Warnf("[LNDHUB] Banned user %s. Not forwarding request", password)
return
}
// then we check whether the "normal" password provided is in the database (it should be not if the user is banned)
user := &lnbits.User{}
tx := w.database.Where("wallet_adminkey = ? COLLATE NOCASE", password).First(user)
if tx.Error != nil {
log.Warnf("[LNDHUB] Could not get wallet admin key %s: %v", password, tx.Error)
return
}
log.Debugf("[LNDHUB] User: %s", telegram.GetUserStr(user.Telegram))
}
// if not, proxy the request
api.Proxy(writer, request, internal.Configuration.Lnbits.Url)
}
// parseBearerAuth parses an HTTP Basic Authentication string.
// "Bearer QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
func parseBearerAuth(auth string) (username, password string, ok bool) {
const prefix = "Bearer "
// Case insensitive prefix match. See Issue 22736.
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
return
}
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
if err != nil {
return
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return
}
return cs[:s], cs[s+1:], true
}
+195 -68
View File
@@ -19,11 +19,13 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"gorm.io/gorm"
db "github.com/LightningTipBot/LightningTipBot/internal/database"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/fiatjaf/go-lnurl"
"github.com/gorilla/mux"
"github.com/nbd-wtf/go-nostr"
log "github.com/sirupsen/logrus"
)
@@ -32,17 +34,19 @@ const (
Endpoint = ".well-known/lnurlp"
MinSendable = 1000 // mSat
MaxSendable = 1_000_000_000
CommentAllowed = 500
CommentAllowed = 2000
)
type Invoice struct {
*telegram.Invoice
Comment string `json:"comment"`
User *lnbits.User `json:"user"`
CreatedAt time.Time `json:"created_at"`
Paid bool `json:"paid"`
PaidAt time.Time `json:"paid_at"`
From string `json:"from"`
Comment string `json:"comment"`
User *lnbits.User `json:"user"`
CreatedAt time.Time `json:"created_at"`
Paid bool `json:"paid"`
PaidAt time.Time `json:"paid_at"`
From string `json:"from"`
Nip57Receipt nostr.Event `json:"nip57_receipt"`
Nip57ReceiptRelays []string `json:"nip57_receipt_relays"`
}
type Lnurl struct {
telegram *tb.Bot
@@ -52,6 +56,7 @@ type Lnurl struct {
buntdb *storage.DB
WebhookServer string
cache telegram.Cache
bot *telegram.TipBot
}
func New(bot *telegram.TipBot) Lnurl {
@@ -63,6 +68,7 @@ func New(bot *telegram.TipBot) Lnurl {
buntdb: bot.Bunt,
telegram: bot.Telegram,
cache: bot.Cache,
bot: bot,
}
}
func (lnurlInvoice Invoice) Key() string {
@@ -81,11 +87,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,14 +109,43 @@ 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)
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)
if len(payerdata) > 0 {
err = json.Unmarshal([]byte(payerdata), &payerData)
if err != nil {
// api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err))
log.Errorf("[handleLnUrl] Couldn't parse payerdata: %v", err)
// log.Errorf("[handleLnUrl] payerdata: %v", payerdata)
}
}
response, err = w.serveLNURLpSecond(username, int64(amount), comment, payerData)
// nostr NIP-57
// the "nostr" query param has a zap request which is a nostr event
// that specifies which nostr note has been zapped.
// here we check wheter its present, the event signature is valid
// and whether the event has the necessary tags that we need (p and relays are necessary, e is optional)
zapEventQuery := request.FormValue("nostr")
var zapEvent nostr.Event
if len(zapEventQuery) > 0 {
err = json.Unmarshal([]byte(zapEventQuery), &zapEvent)
if err != nil {
log.Errorf("[handleLnUrl] Couldn't parse nostr event: %v", err)
} else {
valid, err := zapEvent.CheckSignature()
if !valid || err != nil {
log.Errorf("[handleLnUrl] Nostr NIP-57 zap event signature invalid: %v", err)
return
}
if len(zapEvent.Tags) == 0 || zapEvent.Tags.GetFirst([]string{"p"}) == nil {
// zapEvent.Tags.GetFirst([]string{"e"}) == nil {
log.Errorf("[handleLnUrl] Nostr NIP-57 zap event validation error")
return
}
}
}
response, err = w.serveLNURLpSecond(username, int64(amount), comment, payerData, zapEvent)
}
// check if error was returned from first or second handlers
if err != nil {
@@ -137,7 +180,7 @@ func (w Lnurl) getMetaDataCached(username string) lnurl.Metadata {
// load the user profile picture
if internal.Configuration.Bot.LNURLSendImage {
// get the user from the database
user, tx := findUser(w.database, username)
user, tx := db.FindUser(w.database, username)
if tx.Error == nil && user.Telegram != nil {
addImageToMetaData(w.telegram, &metadata, username, user.Telegram)
}
@@ -148,9 +191,25 @@ func (w Lnurl) getMetaDataCached(username string) lnurl.Metadata {
return metadata
}
// we have our custom LNURLPayParams response object here because we want to
// add nostr nip57 fields to it
type LNURLPayParamsCustom struct {
lnurl.LNURLResponse
Callback string `json:"callback"`
Tag string `json:"tag"`
MaxSendable int64 `json:"maxSendable"`
MinSendable int64 `json:"minSendable"`
EncodedMetadata string `json:"metadata"`
CommentAllowed int64 `json:"commentAllowed"`
PayerData *lnurl.PayerDataSpec `json:"payerData,omitempty"`
AllowNostr bool `json:"allowsNostr,omitempty"`
NostrPubKey string `json:"nostrPubkey,omitempty"`
Metadata lnurl.Metadata `json:"-"`
}
// serveLNURLpFirst serves the first part of the LNURLp protocol with the endpoint
// to call and the metadata that matches the description hash of the second response
func (w Lnurl) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error) {
func (w Lnurl) serveLNURLpFirst(username string) (*LNURLPayParamsCustom, error) {
log.Infof("[LNURL] Serving endpoint for user %s", username)
callbackURL, err := url.Parse(fmt.Sprintf("%s/%s/%s", w.callbackHostname.String(), Endpoint, username))
if err != nil {
@@ -160,7 +219,18 @@ func (w Lnurl) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error)
// produce the metadata including the image
metadata := w.getMetaDataCached(username)
return &lnurl.LNURLPayParams{
// check if the user has added a nostr key for nip57
var allowNostr bool = false
var nostrPubkey string = ""
// if the bot has a nostr private key
if len(internal.Configuration.Nostr.PrivateKey) > 0 {
allowNostr = true
pk := internal.Configuration.Nostr.PrivateKey
pub, _ := nostr.GetPublicKey(pk)
nostrPubkey = pub
}
return &LNURLPayParamsCustom{
LNURLResponse: lnurl.LNURLResponse{Status: api.StatusOk},
Tag: PayRequestTag,
Callback: callbackURL.String(),
@@ -173,18 +243,20 @@ func (w Lnurl) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error)
LightningAddress: &lnurl.PayerDataItemSpec{},
Email: &lnurl.PayerDataItemSpec{},
},
AllowNostr: allowNostr,
NostrPubKey: nostrPubkey,
}, nil
}
// serveLNURLpSecond serves the second LNURL response with the payment request with the correct description hash
func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment string, payerData lnurl.PayerDataValues) (*lnurl.LNURLPayValues, error) {
func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment string, payerData lnurl.PayerDataValues, zapEvent nostr.Event) (*lnurl.LNURLPayValues, error) {
log.Infof("[LNURL] Serving invoice for user %s", username)
if amount_msat < MinSendable || amount_msat > MaxSendable {
// amount is not ok
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: api.StatusError,
Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", MinSendable, MinSendable)},
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
@@ -195,7 +267,11 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
Reason: fmt.Sprintf("Comment too long (max: %d characters).", CommentAllowed)},
}, fmt.Errorf("comment too long")
}
user, tx := findUser(w.database, username)
// get rid of LNURL spam
if amount_msat < 21_000 {
comment = ""
}
user, tx := db.FindUser(w.database, username)
if tx.Error != nil {
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
@@ -210,28 +286,75 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
Reason: fmt.Sprintf("Invalid user.")},
}, fmt.Errorf("[serveLNURLpSecond] user %s not found", username)
}
// get user settings
user2, err := db.FindUserSettings(user, w.bot.DB.Users.Preload("Settings"))
if err != nil {
fmt.Errorf("[serveLNURLpSecond] Couldn't fetch user settings from database: %v", err)
} else {
user = user2
}
// user is ok now create invoice
// set wallet lnbits client
var resp *lnurl.LNURLPayValues
var descriptionHash string
// the same description_hash needs to be built in the second request
metadata := w.getMetaDataCached(username)
// NIP57 ZAPs
// TODO: refactor all this into nip57.go
var nip57Receipt nostr.Event
var zapEventSerializedStr string
var nip57ReceiptRelays []string
// for nip57 use the nostr event as the descriptionHash
if zapEvent.Sig != "" {
log.Infof("[LNURL] nostr zap for user %s", username)
// we calculate the descriptionHash here, create an invoice with it
// and store the invoice in the zap receipt later down the line
zapEventSerialized, err := json.Marshal(zapEvent)
zapEventSerializedStr = fmt.Sprintf("%s", zapEventSerialized)
if err != nil {
log.Println(err)
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: api.StatusError,
Reason: "Couldn't serialize zap event."},
}, err
}
// we extract the relays from the zap request
nip57ReceiptRelaysTags := zapEvent.Tags.GetFirst([]string{"relays"})
if len(fmt.Sprintf("%s", nip57ReceiptRelaysTags)) > 0 {
nip57ReceiptRelays = strings.Split(fmt.Sprintf("%s", nip57ReceiptRelaysTags), " ")
// this tirty method returns slice [ "[relays", "wss...", "wss...", "wss...]" ] – we need to clean it up
if len(nip57ReceiptRelays) > 1 {
// remove the first entry
nip57ReceiptRelays = nip57ReceiptRelays[1:]
// clean up the last entry
len_last_entry := len(nip57ReceiptRelays[len(nip57ReceiptRelays)-1])
nip57ReceiptRelays[len(nip57ReceiptRelays)-1] = nip57ReceiptRelays[len(nip57ReceiptRelays)-1][:len_last_entry-1]
}
// now the relay list is clean!
}
// calculate description hash from the serialized nostr event
descriptionHash = w.Nip57DescriptionHash(zapEventSerializedStr)
} else {
// calculate normal LNURL descriptionhash
// the same description_hash needs to be built in the second request
metadata := w.getMetaDataCached(username)
var payerDataByte []byte
var err error
if payerData.Email != "" || payerData.LightningAddress != "" || payerData.FreeName != "" {
payerDataByte, err = json.Marshal(payerData)
var payerDataByte []byte
var err error
if payerData.Email != "" || payerData.LightningAddress != "" || payerData.FreeName != "" {
payerDataByte, err = json.Marshal(payerData)
if err != nil {
return nil, err
}
} else {
payerDataByte = []byte("")
}
descriptionHash, err = w.DescriptionHash(metadata, string(payerDataByte))
if err != nil {
return nil, err
}
} else {
payerDataByte = []byte("")
}
descriptionHash, err := w.descriptionHash(metadata, string(payerDataByte))
if err != nil {
return nil, err
}
invoice, err := user.Wallet.Invoice(
@@ -255,21 +378,46 @@ func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment str
PaymentHash: invoice.PaymentHash,
Amount: amount_msat / 1000,
}
// nip57 - we need to store the newly created invoice in the zap receipt
if zapEvent.Sig != "" {
pk := internal.Configuration.Nostr.PrivateKey
pub, _ := nostr.GetPublicKey(pk)
nip57Receipt = nostr.Event{
PubKey: pub,
CreatedAt: time.Now(),
Kind: 9735,
Tags: nostr.Tags{
*zapEvent.Tags.GetFirst([]string{"p"}),
[]string{"bolt11", invoice.PaymentRequest},
[]string{"description", zapEventSerializedStr},
},
}
if zapEvent.Tags.GetFirst([]string{"e"}) != nil {
nip57Receipt.Tags = nip57Receipt.Tags.AppendUnique(*zapEvent.Tags.GetFirst([]string{"e"}))
}
nip57Receipt.Sign(pk)
}
// save lnurl invoice struct for later use (will hold the comment or other metadata for a notification when paid)
// also holds Nip57 Zap receipt to send to nostr when invoice is paid
runtime.IgnoreError(w.buntdb.Set(
Invoice{
Invoice: invoiceStruct,
User: user,
Comment: comment,
CreatedAt: time.Now(),
From: extractSenderFromPayerdata(payerData),
Invoice: invoiceStruct,
User: user,
Comment: comment,
CreatedAt: time.Now(),
From: extractSenderFromPayerdata(payerData),
Nip57Receipt: nip57Receipt,
Nip57ReceiptRelays: nip57ReceiptRelays,
}))
// save the invoice Event that will be loaded when the invoice is paid and trigger the comment display callback
runtime.IgnoreError(w.buntdb.Set(
telegram.InvoiceEvent{
Invoice: invoiceStruct,
User: user,
Callback: telegram.InvoiceCallbackLNURLPayReceive,
Invoice: invoiceStruct,
User: user,
Callback: telegram.InvoiceCallbackLNURLPayReceive,
UserCurrency: user.Settings.Display.DisplayCurrency,
}))
return &lnurl.LNURLPayValues{
@@ -281,8 +429,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 {
@@ -302,7 +450,7 @@ func (w Lnurl) metaData(username string) lnurl.Metadata {
// we actually want to find the users username so it looks nicer in the
// metadata description
if strings.HasPrefix(username, "1x") {
user, _ := findUser(w.database, username)
user, _ := db.FindUser(w.database, username)
if user.Telegram.Username != "" {
username = user.Telegram.Username
}
@@ -343,27 +491,6 @@ func isAnonUsername(username string) bool {
}
}
func findUser(database *gorm.DB, username string) (*lnbits.User, *gorm.DB) {
// now check for the user
user := &lnbits.User{}
// check if "username" is actually the user ID
tx := database
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
// asume it's anon_id
tx = database.Where("anon_id = ?", username).First(user)
} else if strings.HasPrefix(username, "0x") {
// asume it's anon_id_sha256
tx = database.Where("anon_id_sha256 = ?", username).First(user)
} else if strings.HasPrefix(username, "1x") {
// asume it's uuid
tx = database.Where("uuid = ?", username).First(user)
} else {
// assume it's a string @username
tx = database.Where("telegram_username = ? COLLATE NOCASE", username).First(user)
}
return user, tx
}
func extractSenderFromPayerdata(payer lnurl.PayerDataValues) string {
if payer.LightningAddress != "" {
return payer.LightningAddress
+28
View File
@@ -0,0 +1,28 @@
package lnurl
import (
"crypto/sha256"
"encoding/hex"
"time"
)
type Tag []string
type Tags []Tag
type NostrEvent struct {
ID string `json:"id"`
PubKey string `json:"pubkey"`
CreatedAt time.Time `json:"created_at"`
Kind int `json:"kind"`
Tags Tags `json:"tags"`
Content string `json:"content"`
Sig string `json:"sig"`
}
// DescriptionHash is the SHA256 hash of the metadata
func (w Lnurl) Nip57DescriptionHash(zapEventSerialized string) string {
hash := sha256.Sum256([]byte(zapEventSerialized))
hashString := hex.EncodeToString(hash[:])
return hashString
}
+21
View File
@@ -6,6 +6,7 @@ import (
"net"
"net/http"
"net/url"
"regexp"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
@@ -20,6 +21,23 @@ const (
ClientTypeTor = "tor"
)
// checks if strings contains http(s)://*.onion
var isOnion = regexp.MustCompile("^https?\\:\\/\\/[\\w\\-\\.]+\\.onion")
// GetClientForScheme returns correct client for url scheme.
// if tld is .onion, function will also return an onion client.
func GetClientForScheme(url *url.URL) (*http.Client, error) {
if isOnion.FindString(url.String()) != "" {
return GetClient(ClientTypeTor)
}
switch url.Scheme {
case "onion":
return GetClient(ClientTypeTor)
default:
return GetClient(ClientTypeClearNet)
}
}
func GetClient(clientType ClientType) (*http.Client, error) {
client := http.Client{
Timeout: 10 * time.Second,
@@ -36,6 +54,9 @@ func GetClient(clientType ClientType) (*http.Client, error) {
if cfg == nil {
return &client, nil
}
if cfg.Host == "" {
return &client, nil
}
proxyURL, _ := url.Parse(cfg.Host)
specialTransport := &http.Transport{}
specialTransport.Proxy = http.ProxyURL(proxyURL)
+56
View File
@@ -0,0 +1,56 @@
package nostr
import (
"fmt"
"net/http"
"github.com/LightningTipBot/LightningTipBot/internal/api"
db "github.com/LightningTipBot/LightningTipBot/internal/database"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/prometheus/common/log"
"gorm.io/gorm"
)
type Nostr struct {
database *gorm.DB
bot *telegram.TipBot
}
func New(bot *telegram.TipBot) Nostr {
return Nostr{
database: bot.DB.Users,
bot: bot,
}
}
func (n Nostr) Handle(writer http.ResponseWriter, request *http.Request) {
username := request.FormValue("name")
if username == "" {
api.NotFoundHandler(writer, fmt.Errorf("[NostrNip05] Form value 'name' is not set"))
return
}
user, tx := db.FindUser(n.database, username)
if tx.Error == nil && user.Telegram != nil {
user, err := db.FindUserSettings(user, n.bot.DB.Users.Preload("Settings"))
if err != nil {
log.Errorf("[NostrNip05] user settings not found")
api.NotFoundHandler(writer, fmt.Errorf("user settings error"))
return
}
if user.Settings.Nostr.PubKey != "" {
data := []byte(fmt.Sprintf(`{
"names":{
"%s":"%s"
}
}
`, username, user.Settings.Nostr.PubKey))
_, err = writer.Write(data)
if err != nil {
log.Errorf("[NostrNip05] Failed responding to user %s", username)
}
}
} else {
log.Errorf("[NostrNip05] user not found")
api.NotFoundHandler(writer, fmt.Errorf("user not found"))
}
}
+2 -1
View File
@@ -2,10 +2,11 @@ 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.v3"
)
+80 -25
View File
@@ -5,72 +5,127 @@ import (
"time"
)
var tickerMap cmap.ConcurrentMap
var functionMap cmap.ConcurrentMap
func init() {
tickerMap = cmap.New()
functionMap = cmap.New()
}
var defaultTickerCoolDown = time.Second * 10
var DefaultTickerDuration = time.Second * 10
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
type ResettableFunctionTicker struct {
// ResettableFunction will reset the user state as soon as tick is delivered.
type ResettableFunction struct {
Ticker *time.Ticker
Timer *time.Timer
ResetChan chan struct{} // channel used to reset the ticker
StopChan chan struct{} // channel used to reset the ticker
duration time.Duration
Started bool
name string
}
type ResettableFunctionTickerOption func(*ResettableFunctionTicker)
type ResettableFunctionTickerOption func(*ResettableFunction)
func WithTicker(t *time.Ticker) ResettableFunctionTickerOption {
return func(a *ResettableFunction) {
a.Ticker = t
}
}
func WithDuration(d time.Duration) ResettableFunctionTickerOption {
return func(a *ResettableFunctionTicker) {
return func(a *ResettableFunction) {
a.duration = d
}
}
func WithTimer(t *time.Timer) ResettableFunctionTickerOption {
return func(a *ResettableFunction) {
a.Timer = t
}
}
func RemoveTicker(name string) {
tickerMap.Remove(name)
functionMap.Remove(name)
}
func GetTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
if t, ok := tickerMap.Get(name); ok {
return t.(*ResettableFunctionTicker)
func Get(name string) (*ResettableFunction, bool) {
if t, ok := functionMap.Get(name); ok {
return t.(*ResettableFunction), ok
}
return nil, false
}
func GetFunction(name string, option ...ResettableFunctionTickerOption) *ResettableFunction {
if t, ok := functionMap.Get(name); ok {
return t.(*ResettableFunction)
} else {
t := NewResettableFunctionTicker(name, option...)
tickerMap.Set(name, t)
t := NewResettableFunction(name, option...)
functionMap.Set(name, t)
return t
}
}
func NewResettableFunctionTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
t := &ResettableFunctionTicker{
func NewResettableFunction(name string, option ...ResettableFunctionTickerOption) *ResettableFunction {
t := &ResettableFunction{
ResetChan: make(chan struct{}, 1),
StopChan: make(chan struct{}, 1),
name: name,
}
if t.duration == 0 {
t.duration = DefaultTickerDuration
}
for _, opt := range option {
opt(t)
}
if t.duration == 0 {
t.duration = defaultTickerCoolDown
}
t.Ticker = time.NewTicker(t.duration)
return t
}
func (t *ResettableFunctionTicker) Do(f func()) {
// Do will listen for timers and invoke functionCallback on tick.
func (t *ResettableFunction) Do(functionCallback func()) {
t.Started = true
tickerMap.Set(t.name, t)
// persist function
functionMap.Set(t.name, t)
go func() {
for {
if t.Timer != nil {
// timer is set. checking event
select {
case <-t.Timer.C:
functionCallback()
return
default:
}
}
if t.Ticker != nil {
// ticker is set. checking event
select {
case <-t.Ticker.C:
// ticker delivered signal. do function functionCallback
functionCallback()
return
default:
}
}
// check stop and reset channels
select {
case <-t.Ticker.C:
// ticker delivered signal. do function f
f()
case <-t.StopChan:
if t.Timer != nil {
t.Timer.Stop()
}
if t.Ticker != nil {
t.Ticker.Stop()
}
return
case <-t.ResetChan:
// reset signal received. creating new ticker.
t.Ticker = time.NewTicker(t.duration)
if t.Ticker != nil {
t.Ticker.Reset(t.duration)
}
if t.Timer != nil {
t.Timer.Reset(t.duration)
}
default:
break
}
time.Sleep(time.Millisecond * 500)
}
}()
}
+4 -3
View File
@@ -5,13 +5,14 @@ import (
"time"
)
// todo -- use function.go instead!
// var retryMap cmap.ConcurrentMap
// func init() {
// retryMap = cmap.New()
// }
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
// ResettableFunction will reset the user state as soon as tick is delivered.
type FunctionRetry struct {
Ticker *time.Ticker
duration time.Duration
@@ -35,14 +36,14 @@ func NewRetryTicker(ctx context.Context, name string, option ...FunctionRetryOpt
opt(t)
}
if t.duration == 0 {
t.duration = defaultTickerCoolDown
t.duration = DefaultTickerDuration
}
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)
functionMap.Set(t.name, t)
go func() {
for {
select {
+2
View File
@@ -2,6 +2,7 @@ package storage
import (
"encoding/json"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/tidwall/buntdb"
@@ -56,6 +57,7 @@ func (db *DB) Get(object Storable) error {
}
err = json.Unmarshal([]byte(val), object)
if err != nil {
fmt.Println(err)
return err
}
return nil
+29 -4
View File
@@ -4,10 +4,11 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
@@ -20,6 +21,12 @@ import (
tb "gopkg.in/lightningtipbot/telebot.v3"
)
// amountsMap maps string to int64 amounts
var amountsMap = map[string]int64{
"🍌": 777,
"🥜": 69,
}
func getArgumentFromCommand(input string, which int) (output string, err error) {
if len(strings.Split(input, " ")) < which+1 {
return "", fmt.Errorf("message doesn't contain enough arguments")
@@ -34,11 +41,21 @@ func decodeAmountFromCommand(input string) (amount int64, err error) {
// log.Errorln(errmsg)
return 0, fmt.Errorf(errmsg)
}
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) {
// replace occurances of comma with dot
input = strings.Replace(input, ",", ".", -1)
// replace strings in amountsMap with their integer values
for k, v := range amountsMap {
input = strings.Replace(input, k, strconv.FormatInt(v, 10), -1)
}
// 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)
@@ -81,6 +98,14 @@ func getAmount(input string) (amount int64, err error) {
return amount, err
}
func SatoshisToFiat(amount int64, currency string) (fiat float64, err error) {
if !(price.Price[currency] > 0) {
return 0, fmt.Errorf("price is zero")
}
fiat = float64(amount) / 100_000_000 * price.Price[currency]
return fiat, nil
}
type EnterAmountStateData struct {
ID string `json:"ID"` // holds the ID of the tx object in bunt db
Type string `json:"Type"` // holds type of the tx in bunt db (needed for type checking)
@@ -140,7 +165,7 @@ func (bot *TipBot) enterAmountHandler(ctx intercept.Context) (intercept.Context,
return ctx, err
}
amount, err := getAmount(ctx.Message().Text)
amount, err := GetAmount(ctx.Message().Text)
if err != nil {
log.Warnf("[enterAmountHandler] %s", err.Error())
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
+1
View File
@@ -2,6 +2,7 @@ package telegram
import (
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
+2
View File
@@ -63,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)
@@ -134,6 +135,7 @@ func (bot *TipBot) Start() {
// start the telegram bot
go bot.Telegram.Start()
go bot.restartPersistedTickets()
// gracefully shutdown
exit := make(chan os.Signal, 1) // we need to reserve to buffer size 1, so the notifier are not blocked
// we need to catch SIGTERM and SIGSTOP
+37 -7
View File
@@ -3,7 +3,9 @@ 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.v3"
@@ -11,16 +13,24 @@ import (
// 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"
MainMenuCommandWebApp = "🗳️ App"
MainMenuCommandBalance = "Balance"
MainMenuCommandInvoice = "⚡️ Invoice"
MainMenuCommandHelp = "📖 Help"
MainMenuCommandSend = "⤴️"
SendMenuCommandEnter = "👤 Enter"
)
var (
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)
@@ -31,9 +41,11 @@ var (
)
func init() {
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu, btnHelpMainMenu),
// mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu), // TODO: fix btnSendMainMenu
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnHelpMainMenu),
)
}
@@ -58,6 +70,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
@@ -75,11 +102,14 @@ func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
log.Tracef("[appendMainMenu] user %s balance %d sat", GetUserStr(user.Telegram), amount)
MainMenuCommandBalance := fmt.Sprintf("%s %d sat", MainMenuCommandBalance, amount)
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu),
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu, btnHelpMainMenu),
)
}
bot.appendWebAppLinkToButton(&btnWebAppMainMenu, user)
mainMenu.Reply(
mainMenu.Row(btnBalanceMainMenu),
// mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnSendMainMenu, btnHelpMainMenu), // TODO: fix btnSendMainMenu
mainMenu.Row(btnInvoiceMainMenu, btnWebAppMainMenu, btnHelpMainMenu),
)
}
}
@@ -98,7 +128,7 @@ func (bot *TipBot) makeContactsButtons(ctx context.Context) []tb.Btn {
// 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
+13 -1
View File
@@ -11,12 +11,13 @@ import (
"strconv"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/database"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/eko/gocache/store"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/database"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/tidwall/buntdb"
@@ -35,18 +36,29 @@ type Databases struct {
}
const (
JoinTicketIndex = "join-ticket:*"
MessageOrderedByReplyToFrom = "message.reply_to_message.from.id"
TipTooltipKeyPattern = "tip-tool-tip:*"
)
func createBunt(file string) *storage.DB {
t1 := time.Now()
// create bunt database
bunt := storage.NewBunt(file)
log.Infof("[blunt] loaded file in %s", time.Since(t1))
// create bunt database index for ascending (searching) TipTooltips
err := bunt.CreateIndex(MessageOrderedByReplyToFrom, TipTooltipKeyPattern, buntdb.IndexJSON(MessageOrderedByReplyToFrom))
log.Infof("[blunt] index 1 created in %s", time.Since(t1))
if err != nil {
panic(err)
}
err = bunt.CreateIndex("join-ticket", JoinTicketIndex, buntdb.IndexString)
log.Infof("[blunt] index 2 created in %s", time.Since(t1))
if err != nil {
panic(err)
}
log.Infof("[blunt] total time: %s", time.Since(t1))
return bunt
}
+35 -5
View File
@@ -2,13 +2,18 @@ package telegram
import (
"context"
"encoding/json"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/fiatjaf/go-lnurl"
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/str"
@@ -50,11 +55,24 @@ func (bot TipBot) donationHandler(ctx intercept.Context) (intercept.Context, err
_, err = bot.askForAmount(ctx, "", "CreateDonationState", 0, 0, m.Text)
return ctx, err
}
amount = amount * 1000
// 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)))
r, err := http.NewRequest(http.MethodGet, donationEndpoint, nil)
if err != nil {
log.Errorln(err)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
// Create query parameters
params := url.Values{}
params.Set("amount", strconv.FormatInt(amount, 10))
params.Set("comment", fmt.Sprintf("from %s bot %s", GetUserStr(user.Telegram), GetUserStr(bot.Telegram.Me)))
// Set the query parameters in the URL
r.URL.RawQuery = params.Encode()
resp, err := http.DefaultClient.Do(r)
if err != nil {
log.Errorln(err)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
@@ -66,11 +84,23 @@ func (bot TipBot) donationHandler(ctx intercept.Context) (intercept.Context, err
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
pv := lnurl.LNURLPayValues{}
err = json.Unmarshal(body, &pv)
if err != nil {
log.Errorln(err)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
if pv.Status == "ERROR" || len(pv.PR) < 1 {
log.Errorln(err)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return ctx, err
}
// send donation invoice
// user := LoadUser(ctx)
// bot.trySendMessage(user.Telegram, string(body))
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: string(body)}, bot.Client)
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: string(pv.PR)}, bot.Client)
if err != nil {
userStr := GetUserStr(user.Telegram)
errmsg := fmt.Sprintf("[/donate] Donation failed for user %s: %s", userStr, err)
@@ -88,7 +118,7 @@ func (bot TipBot) donationHandler(ctx intercept.Context) (intercept.Context, err
func init() {
var sb strings.Builder
_, err := io.Copy(&sb, rot13Reader{strings.NewReader("uggcf://ya.gvcf/qbangr/%q?sebz=%f&obg=%f")})
_, err := io.Copy(&sb, rot13Reader{strings.NewReader("uggcf://ya.gvcf/.jryy-xabja/yaheyc/YvtugavatGvcObg")})
if err != nil {
panic(err)
}
+1 -1
View File
@@ -62,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)
}
+2 -1
View File
@@ -5,6 +5,7 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
tb "gopkg.in/lightningtipbot/telebot.v3"
"time"
)
func (bot *TipBot) fileHandler(ctx intercept.Context) (intercept.Context, error) {
@@ -16,7 +17,7 @@ func (bot *TipBot) fileHandler(ctx intercept.Context) (intercept.Context, error)
if c := stateCallbackMessage[user.StateKey]; c != nil {
// found ctx for this state
// now looking for user state reset ticker
ticker := runtime.GetTicker(user.ID)
ticker := runtime.GetFunction(user.ID, runtime.WithTicker(time.NewTicker(runtime.DefaultTickerDuration)))
if !ticker.Started {
ticker.Do(func() {
ResetUserState(user, bot)
+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", GetUserStr(user.Telegram)), "", 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, GetUserStr(user.Telegram))
// 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, GetUserStr(user.Telegram))
}
}
}
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", GetUserStr(user.Telegram)),
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", GetUserStr(user.Telegram), 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
}
+73
View File
@@ -0,0 +1,73 @@
package telegram
import (
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/gpt"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
uuid "github.com/satori/go.uuid"
log "github.com/sirupsen/logrus"
"gopkg.in/lightningtipbot/telebot.v3"
)
func (bot *TipBot) gptHandler(ctx intercept.Context) (intercept.Context, error) {
question := GetMemoFromCommand(ctx.Text(), 1)
req := gpt.Request{
Action: "next",
Model: "text-davinci-002-render",
Messages: []gpt.Messages{{
ID: uuid.NewV4().String(),
Role: "user",
Content: gpt.Content{
ContentType: "text",
Parts: []string{question},
},
},
},
}
conversationIdCacheKey := fmt.Sprintf("conversation_%d", ctx.Chat().ID)
parentIdCacheKey := fmt.Sprintf("conversation_parent_%d", ctx.Chat().ID)
conversationId, _ := bot.Cache.Get(conversationIdCacheKey)
if parentId, _ := bot.Cache.Get(parentIdCacheKey); parentId != nil {
req.ParentMessageID = parentId.(string)
}
if conversationId != nil {
req.ConversationId = conversationId.(string)
}
cbc := 0
var msg *telebot.Message
completion, err := gpt.GetRawCompletion(ctx, req, func(s string) {
cbc++
if ctx.Chat().Type == telebot.ChatPrivate {
if cbc == 20 {
msg = bot.trySendMessageEditable(ctx.Sender(), s)
return
}
} else {
if cbc == 20 {
msg = bot.tryReplyMessage(ctx.Message(), s)
return
}
}
if cbc%20 == 0 {
bot.tryEditMessage(msg, s)
}
})
if err != nil {
bot.tryEditMessage(ctx.Message(), fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "Could not create completion."))
return ctx, err
}
answer := completion.Message.Content.Parts[len(completion.Message.Content.Parts)-1]
bot.tryEditMessage(msg, answer)
err = bot.Cache.Set(conversationIdCacheKey, completion.ConversationID, nil)
if err != nil {
log.Errorf("[/gpt] error setting conversation id %s: %v", conversationIdCacheKey, err)
}
err = bot.Cache.Set(parentIdCacheKey, completion.Message.ID, nil)
if err != nil {
log.Errorf("[/gpt] error setting parent message id %s: %v", parentIdCacheKey, err)
}
log.Infof("[/gpt] \"%s\" => \"%s\"", question, answer)
return ctx, nil
}
+159 -26
View File
@@ -5,7 +5,9 @@ import (
"context"
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
@@ -22,6 +24,30 @@ import (
tb "gopkg.in/lightningtipbot/telebot.v3"
)
type JoinTicket struct {
Sender *tb.User `json:"sender"`
Message *tb.Message `json:"message"`
CreatedTimestamp time.Time `json:"created_timestamp"`
Ticket *Ticket `json:"ticket"`
}
func (jt JoinTicket) Key() string {
return fmt.Sprintf("join-ticket:%d_%d", jt.Message.Chat.ID, jt.Sender.ID)
}
func (jt JoinTicket) Type() EventType {
return EventTypeTicketInvoice
}
func (bot *TipBot) loadGroup(groupName string) (*Group, error) {
group := &Group{}
tx := bot.DB.Groups.Where("id = ? COLLATE NOCASE", groupName).First(group)
if tx.Error != nil {
return nil, tx.Error
}
return group, nil
}
type Ticket struct {
Price int64 `json:"price"`
Memo string `json:"memo"`
@@ -83,8 +109,9 @@ var (
btnPayTicket = paymentConfirmationMenu.Data("✅ Pay", "pay_ticket")
)
var (
groupInvoiceMemo = "🎟 Ticket for group %s"
const (
groupInvoiceMemo = "🎟 Ticket for group %s"
groupInvoiceCommissionMemo = "🎟 Commission for group %s"
)
// groupHandler is called if the /group <cmd> command is invoked. It then decides with other
@@ -92,15 +119,18 @@ var (
func (bot TipBot) groupHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
splits := strings.Split(m.Text, " ")
user := LoadUser(ctx)
// user := LoadUser(ctx)
if len(splits) == 1 {
// command: /group
if ctx.Message().Private() {
// /group help message
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)))
}
}
// 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" {
@@ -109,6 +139,9 @@ func (bot TipBot) groupHandler(ctx intercept.Context) (intercept.Context, error)
if splits[1] == "add" {
return bot.addGroupHandler(ctx)
}
if splits[1] == "ticket" {
return bot.handleJoinTicketPayWall(ctx)
}
if splits[1] == "remove" {
// todo -- implement this
// return bot.addGroupHandler(ctx, m)
@@ -213,6 +246,11 @@ func (bot TipBot) groupRequestJoinHandler(ctx intercept.Context) (intercept.Cont
// 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) {
confirmText, confirmationMenu := bot.getSendPayButton(ctx, ticket)
bot.trySendMessageEditable(ctx.Message().Chat, confirmText, confirmationMenu)
return ctx, nil
}
func (bot *TipBot) getSendPayButton(ctx intercept.Context, ticket TicketEvent) (string, *tb.ReplyMarkup) {
// object that holds all information about the send payment
// // // create inline buttons
btnPayTicket := ticketPayConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "pay_ticket", ticket.Base.ID)
@@ -221,11 +259,10 @@ func (bot *TipBot) groupSendPayButtonHandler(ctx intercept.Context, ticket Ticke
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
// if len(ticket.Group.Ticket.Memo) > 0 {
// confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(ticket.Group.Ticket.Memo))
// }
return confirmText, ticketPayConfirmationMenu
}
// groupConfirmPayButtonHandler is invoked if th user clicks the pay button.
@@ -266,13 +303,17 @@ func (bot *TipBot) groupConfirmPayButtonHandler(ctx intercept.Context) (intercep
if err != nil {
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of %s: %s", GetUserStr(user.Telegram), err)
err = fmt.Errorf(i18n.Translate(ticketEvent.LanguageCode, "invoiceUndefinedErrorMessage"))
bot.tryEditMessage(c, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
if ticketEvent.Callback != InvoiceCallbackPayJoinTicket {
bot.tryEditMessage(c, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
}
log.Errorln(errmsg)
return ctx, err
}
// if this was a join-ticket, we want to delete the invoice message
// update the message and remove the button
bot.tryEditMessage(c, i18n.Translate(ticketEvent.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
return ctx, nil
}
@@ -324,23 +365,16 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
bot.trySendMessage(ticketEvent.Payer.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupClickToJoinMessage"), resp.Result.InviteLink, ticketEvent.Group.Title))
// send a notification to the group that sold the ticket
bot.trySendMessage(&tb.Chat{ID: ticketEvent.Group.ID}, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupTicketIssuedGroupMessage"), GetUserStr(ticketEvent.Payer.Telegram)))
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 {
if commissionSat := getTicketCommission(ticketEvent.Group.Ticket); commissionSat > 0 {
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{
@@ -366,12 +400,111 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
errmsg := fmt.Sprintf("could not get balance of user %s", GetUserStr(ticketEvent.Payer.Telegram))
log.Errorln(errmsg)
}
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoiceCommission"), ticketSat, commissionSat, ticketEvent.Group.Title, GetUserStr(ticketEvent.Payer.Telegram)))
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, GetUserStr(ticketEvent.Payer.Telegram)))
bot.trySendMessage(ticketEvent.User.Telegram, fmt.Sprintf(i18n.Translate(ticketEvent.LanguageCode, "groupReceiveTicketInvoice"), ticketSat, ticketEvent.Group.Title, GetUserStrMd(ticketEvent.Payer.Telegram)))
}
}
func (bot TipBot) handleJoinTicketPayWall(ctx intercept.Context) (intercept.Context, error) {
var err error
var cmd string
if cmd, err = getArgumentFromCommand(ctx.Message().Text, 2); err == nil {
switch strings.TrimSpace(strings.ToLower(cmd)) {
case "del":
fallthrough
case "delete":
fallthrough
case "remove":
return bot.removeJoinTicketPayWallHandler(ctx)
default:
return bot.addJoinTicketPayWallHandler(ctx)
}
}
return ctx, err
}
func (bot TipBot) removeJoinTicketPayWallHandler(ctx intercept.Context) (intercept.Context, error) {
groupName := strconv.FormatInt(ctx.Chat().ID, 10)
tx := bot.DB.Groups.Where("id = ? COLLATE NOCASE", groupName).Delete(&Group{})
if tx.Error != nil {
return ctx, tx.Error
}
bot.trySendMessage(ctx.Message().Chat, "🎟 Ticket removed.")
return ctx, nil
}
// addJoinTicketPayWallHandler is invoked if the user calls the "/group ticket" command
func (bot TipBot) addJoinTicketPayWallHandler(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 ticket <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 := strconv.FormatInt(ctx.Chat().ID, 10)
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("id = ? 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, 2); 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, Translate(ctx, "groupAddedMessagePublic"))
return ctx, nil
}
// addGroupHandler is invoked if the user calls the "/group add" command
func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
@@ -412,7 +545,7 @@ func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, err
amount := int64(0) // default amount is zero
if amount_str, err := getArgumentFromCommand(m.Text, 3); err == nil {
amount, err = getAmount(amount_str)
amount, err = GetAmount(amount_str)
if err != nil {
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
return ctx, err
@@ -439,7 +572,7 @@ func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, err
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))
bot.trySendMessage(m.Chat, fmt.Sprintf(Translate(ctx, "groupAddedMessagePrivate"), str.MarkdownEscape(m.Chat.Title), group.Name, group.Ticket.Price, GetUserStrMd(bot.Telegram.Me), group.Name))
return ctx, nil
}
+166 -7
View File
@@ -99,8 +99,24 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
},
},
},
// {
// Endpoints: []interface{}{"/generate"},
// Handler: bot.generateImages,
// Interceptor: &Interceptor{
// Before: []intercept.Func{
// bot.requirePrivateChatInterceptor,
// bot.localizerInterceptor,
// bot.logMessageInterceptor,
// bot.loadUserInterceptor,
// bot.lockInterceptor,
// },
// OnDefer: []intercept.Func{
// bot.unlockInterceptor,
// },
// },
// },
{
Endpoints: []interface{}{"/tip", "/t", "/honk"},
Endpoints: []interface{}{"/tip", "/t", "/honk", "/zap"},
Handler: bot.tipHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
@@ -148,6 +164,38 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
},
},
},
{
Endpoints: []interface{}{"/set"},
Handler: bot.settingHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{"/nostr"},
Handler: bot.nostrHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{"/node"},
Handler: bot.nodeHandler,
@@ -172,6 +220,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -210,6 +259,22 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
bot.unlockInterceptor,
}},
},
// {
// Endpoints: []interface{}{"/gpt", "/chat"},
// Handler: bot.gptHandler,
// Interceptor: &Interceptor{
// Before: []intercept.Func{
// bot.localizerInterceptor,
// bot.logMessageInterceptor,
// bot.requireUserInterceptor,
// bot.lockInterceptor,
// },
// OnDefer: []intercept.Func{
// bot.unlockInterceptor,
// },
// },
// },
{
Endpoints: []interface{}{"/balance", &btnBalanceMainMenu},
Handler: bot.balanceHandler,
@@ -261,6 +326,25 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
},
},
},
// previously, this was the send menu but it
// was replaced with the webapp
// {
// Endpoints: []interface{}{&btnWebAppMainMenu},
// Handler: bot.keyboardSendHandler,
// Interceptor: &Interceptor{
// Before: []intercept.Func{
// bot.localizerInterceptor,
// bot.logMessageInterceptor,
// bot.requireUserInterceptor,
// bot.loadReplyToInterceptor,
// bot.lockInterceptor,
// },
// OnDefer: []intercept.Func{
// bot.unlockInterceptor,
// },
// },
// },
{
Endpoints: []interface{}{"/transactions"},
Handler: bot.transactionsHandler,
@@ -280,6 +364,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -295,6 +380,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -321,7 +407,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Endpoints: []interface{}{"/tipjar", "/spendendose"},
Handler: bot.tipjarHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.logMessageInterceptor,
@@ -337,7 +422,6 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Endpoints: []interface{}{"/help", &btnHelpMainMenu},
Handler: bot.helpHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.logMessageInterceptor,
@@ -385,8 +469,8 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Endpoints: []interface{}{"/advanced"},
Handler: bot.advancedHelpHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
@@ -401,8 +485,24 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Endpoints: []interface{}{"/link"},
Handler: bot.lndhubHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{"/api"},
Handler: bot.apiHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
@@ -417,8 +517,8 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Endpoints: []interface{}{"/lnurl"},
Handler: bot.lnurlHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
@@ -429,12 +529,27 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
},
},
},
// group join
{
Endpoints: []interface{}{tb.OnUserJoined, tb.OnAddedToGroup},
Handler: bot.handleTelegramNewMember,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.tryLoadUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
// group tickets
{
Endpoints: []interface{}{"/group"},
Handler: bot.groupHandler,
Interceptor: &Interceptor{
Before: []intercept.Func{
bot.localizerInterceptor,
bot.logMessageInterceptor,
@@ -471,6 +586,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -548,6 +664,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -563,6 +680,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -578,6 +696,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -593,6 +712,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -608,6 +728,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -623,6 +744,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -638,6 +760,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -653,6 +776,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -669,10 +793,12 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
bot.singletonCallbackInterceptor,
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
bot.answerCallbackInterceptor,
},
},
},
@@ -684,6 +810,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -699,6 +826,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -714,6 +842,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -729,6 +858,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -744,6 +874,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -759,6 +890,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -774,6 +906,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -789,6 +922,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -803,6 +937,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -817,6 +952,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -831,6 +967,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -845,6 +982,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -859,6 +997,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -874,6 +1013,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -889,6 +1029,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -904,6 +1045,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -919,6 +1061,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -934,6 +1077,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -949,6 +1093,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -964,6 +1109,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -979,6 +1125,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -994,6 +1141,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1008,6 +1156,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1022,6 +1171,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1036,6 +1186,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1051,6 +1202,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1065,6 +1217,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1079,6 +1232,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1093,6 +1247,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1107,6 +1262,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1121,6 +1277,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1135,6 +1292,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
@@ -1149,6 +1307,7 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
Before: []intercept.Func{
bot.localizerInterceptor,
bot.loadUserInterceptor,
bot.answerCallbackInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
+1 -1
View File
@@ -274,7 +274,7 @@ func (bot *TipBot) inlineReceiveInvoice(ctx intercept.Context, inlineReceive *In
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
return
}
invoice, err := bot.createInvoiceWithEvent(ctx, inlineReceive.To, inlineReceive.Amount, fmt.Sprintf("Pay to %s", GetUserStr(inlineReceive.To.Telegram)), InvoiceCallbackInlineReceive, inlineReceive.ID)
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"))
+7 -4
View File
@@ -59,10 +59,9 @@ func (bot TipBot) idInterceptor(ctx intercept.Context) (intercept.Context, error
}
// 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 {
@@ -132,6 +131,10 @@ func (bot TipBot) loadUserInterceptor(ctx intercept.Context) (intercept.Context,
}
return ctx, nil
}
func (bot TipBot) tryLoadUserInterceptor(ctx intercept.Context) (intercept.Context, error) {
ctx, _ = bot.requireUserInterceptor(ctx)
return ctx, nil
}
// loadReplyToInterceptor Loading the Telegram user with message intercept
func (bot TipBot) loadReplyToInterceptor(ctx intercept.Context) (intercept.Context, error) {
+61 -13
View File
@@ -8,6 +8,7 @@ import (
"time"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/nbd-wtf/go-nostr"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
@@ -40,6 +41,8 @@ func initInvoiceEventCallbacks(bot *TipBot) {
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},
InvoiceCallbackPayJoinTicket: EventHandler{Function: bot.stopJoinTicketTimer, Type: EventTypeInvoice},
}
}
@@ -51,6 +54,8 @@ const (
InvoiceCallbackLNURLPayReceive
InvoiceCallbackGroupTicket
InvoiceCallbackSatdressProxy
InvoiceCallbackGenerateDalle
InvoiceCallbackPayJoinTicket
)
const (
@@ -84,6 +89,7 @@ type InvoiceEvent struct {
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
UserCurrency string `json:"usercurrency,omitempty"` // the currency a user selected
}
func (invoiceEvent InvoiceEvent) Type() EventType {
@@ -111,6 +117,8 @@ func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, err
// check and print all commands
bot.anyTextHandler(ctx)
user := LoadUser(ctx)
// load user settings
user, err := GetLnbitsUserWithSettings(user.Telegram, *bot)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
@@ -142,7 +150,13 @@ func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, err
creatingMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
log.Debugf("[/invoice] Creating invoice for %s of %d sat.", userStr, amount)
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, InvoiceCallbackGeneric, "")
currency := user.Settings.Display.DisplayCurrency
if currency == "" {
currency = "BTC"
}
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, currency, InvoiceCallbackGeneric, "")
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
@@ -168,7 +182,7 @@ func (bot *TipBot) invoiceHandler(ctx intercept.Context) (intercept.Context, err
return ctx, nil
}
func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User, amount int64, memo string, callback int, callbackData string) (InvoiceEvent, error) {
func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User, amount int64, memo string, currency string, callback int, callbackData string) (InvoiceEvent, error) {
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Out: false,
@@ -190,6 +204,7 @@ func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User
Callback: callback,
CallbackData: callbackData,
LanguageCode: ctx.Value("publicLanguageCode").(string),
UserCurrency: currency,
}
// save invoice struct for later use
runtime.IgnoreError(bot.Bunt.Set(invoiceEvent))
@@ -205,17 +220,30 @@ func (bot *TipBot) notifyInvoiceReceivedEvent(event Event) {
log.Errorln(errmsg)
}
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
if invoiceEvent.UserCurrency == "" || strings.ToLower(invoiceEvent.UserCurrency) == "btc" {
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
} else {
fiatAmount, err := SatoshisToFiat(invoiceEvent.Amount, strings.ToUpper(invoiceEvent.UserCurrency))
if err != nil {
log.Errorln(err)
// fallback to satoshis
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
return
}
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedCurrencyMessage"), invoiceEvent.Amount, fiatAmount, strings.ToUpper(invoiceEvent.UserCurrency)))
}
}
type LNURLInvoice struct {
*Invoice
Comment string `json:"comment"`
User *lnbits.User `json:"user"`
CreatedAt time.Time `json:"created_at"`
Paid bool `json:"paid"`
PaidAt time.Time `json:"paid_at"`
From string `json:"from"`
Comment string `json:"comment"`
User *lnbits.User `json:"user"`
CreatedAt time.Time `json:"created_at"`
Paid bool `json:"paid"`
PaidAt time.Time `json:"paid_at"`
From string `json:"from"`
Nip57Receipt nostr.Event `json:"nip57_receipt"`
Nip57ReceiptRelays []string `json:"nip57_receipt_relays"`
}
func (lnurlInvoice LNURLInvoice) Key() string {
@@ -224,20 +252,40 @@ func (lnurlInvoice LNURLInvoice) Key() string {
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)
if err == nil {
// filter: if tx.Comment includes a URL, return if tx.Amount is less than 100 sat
if len(tx.Comment) > 0 && tx.Amount < 100 {
if strings.Contains(tx.Comment, "http") {
log.Debugf("[lnurl-p] Filtered LNURL comment for %s of %d sat.", GetUserStr(invoiceEvent.User.Telegram), tx.Amount)
return
}
}
if tx.Amount < 21 {
log.Debugf("[lnurl-p] Filtered LNURL comment for %s of %d sat.", GetUserStr(invoiceEvent.User.Telegram), tx.Amount)
return
}
// notify user with LNURL comment and sender Information
if len(tx.Comment) > 0 {
if len(tx.From) == 0 {
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(tx.Comment)))
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(tx.Comment)), tb.NoPreview)
} else {
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("✉️ From `%s`: %s", tx.From, str.MarkdownEscape(tx.Comment)))
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("✉️ From `%s`: %s", tx.From, str.MarkdownEscape(tx.Comment)), tb.NoPreview)
}
} else if len(tx.From) > 0 {
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("From `%s`", str.MarkdownEscape(tx.From)))
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("From `%s`", str.MarkdownEscape(tx.From)), tb.NoPreview)
}
// send out NIP57 zap receipt
if len(tx.Nip57Receipt.Sig) > 0 {
// zapEventSerialized, _ := json.Marshal(tx.Nip57Receipt)
bot.trySendMessage(tx.User.Telegram, "💜 This was a zap on nostr.")
go bot.publishNostrEvent(tx.Nip57Receipt, tx.Nip57ReceiptRelays)
}
}
}
+17 -20
View File
@@ -20,22 +20,9 @@ func (bot *TipBot) lndhubHandler(ctx intercept.Context) (intercept.Context, erro
bot.trySendMessage(m.Sender, Translate(ctx, "couldNotLinkMessage"))
return ctx, fmt.Errorf("invalid configuration")
}
// check and print all commands
bot.anyTextHandler(ctx)
// 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)
@@ -48,14 +35,24 @@ func (bot *TipBot) lndhubHandler(ctx intercept.Context) (intercept.Context, erro
}
// 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"), tb.Silent)
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
}
+7 -3
View File
@@ -97,7 +97,7 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx intercept.Context) (intercept.Con
// 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
@@ -107,7 +107,7 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx intercept.Context) (intercept.Con
}
var sentsigres lnurl.LNURLResponse
client, err := network.GetClient(network.ClientTypeClearNet)
client, err := network.GetClientForScheme(p.CallbackURL)
if err != nil {
return ctx, err
}
@@ -125,7 +125,11 @@ func (bot *TipBot) confirmLnurlAuthHandler(ctx intercept.Context) (intercept.Con
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)
}
+32 -18
View File
@@ -1,6 +1,7 @@
package telegram
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
@@ -25,21 +26,22 @@ import (
// 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
// at this point, the user hans't necessarily entered an amount yet
func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPayState) {
// lnurlPayHandler is invoked when the first lnurl response was a lnurlpay response
// at this point, the user hasn't necessarily entered an amount yet
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))
@@ -76,11 +78,18 @@ func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPaySta
log.Warnf("[lnurlPayHandler] Error: %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
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(payParams.Set(payParams, bot.Bunt))
@@ -91,7 +100,7 @@ func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPaySta
} else if amount_err != nil || amount < 1 {
// // no amount was entered, set user state and ask for amount
bot.askForAmount(ctx, id, "LnurlPayState", payParams.LNURLPayParams.MinSendable, payParams.LNURLPayParams.MaxSendable, m.Text)
return
return ctx, nil
}
// We need to save the pay state in the user state so we can load the payment in the next ctx
@@ -99,12 +108,12 @@ func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPaySta
if err != nil {
log.Errorf("[lnurlPayHandler] Error: %s", 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)
return
return ctx, nil
}
// lnurlPayHandlerSend is invoked when the user has delivered an amount and is ready to pay
@@ -145,13 +154,13 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
// LnurlPayState loaded
client, err := network.GetClient(network.ClientTypeClearNet)
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
client, err := network.GetClientForScheme(callbackUrl)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
@@ -187,15 +196,20 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context
if len(response2.Reason) > 0 {
error_reason = response2.Reason
}
log.Errorf("[lnurlPayHandler] Error in LNURLPayValues: %s", error_reason)
log.Errorf("[lnurlPayHandlerSend] Error in LNURLPayValues: %s", error_reason)
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
return ctx, fmt.Errorf("Error in LNURLPayValues: %s", error_reason)
return ctx, fmt.Errorf("error in LNURLPayValues: %s", error_reason)
}
// all good
lnurlPayState.LNURLPayValues = response2
// add result to persistent struct
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
bot.Telegram.Delete(statusMsg)
// store success action in context for printing after the payHandler
ctx.Context = context.WithValue(ctx, "SuccessAction", lnurlPayState.LNURLPayValues.SuccessAction)
m.Text = fmt.Sprintf("/pay %s", response2.PR)
return bot.payHandler(ctx)
}
+28 -14
View File
@@ -42,21 +42,35 @@ 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
@@ -232,13 +246,13 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
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(handler.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
}
@@ -254,7 +268,7 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
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
@@ -266,25 +280,25 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
callbackUrl.RawQuery = qs.Encode()
// lnurlWithdrawState loaded
client, err := network.GetClient(network.ClientTypeClearNet)
client, err := network.GetClientForScheme(callbackUrl)
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(handler.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, 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(handler.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
}
@@ -293,12 +307,12 @@ func (bot *TipBot) confirmWithdrawHandler(ctx intercept.Context) (intercept.Cont
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"))
}
+26 -10
View File
@@ -2,6 +2,8 @@ package telegram
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/url"
@@ -22,7 +24,7 @@ import (
tb "gopkg.in/lightningtipbot/telebot.v3"
)
func (bot TipBot) cancelLnUrlHandler(c *tb.Callback) {
func (bot *TipBot) cancelLnUrlHandler(c *tb.Callback) {
}
// lnurlHandler is invoked on /lnurl command
@@ -65,7 +67,7 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error
// 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 {
@@ -91,7 +93,7 @@ func (bot *TipBot) lnurlHandler(ctx intercept.Context) (intercept.Context, error
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
@@ -142,7 +144,7 @@ func UserGetLNURL(user *lnbits.User) (string, error) {
}
func UserGetAnonLNURL(user *lnbits.User) (string, error) {
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, fmt.Sprint(user.AnonIDSha256))
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, user.AnonIDSha256)
lnurlEncode, err := lnurl.LNURLEncode(callback)
if err != nil {
return "", err
@@ -151,7 +153,7 @@ func UserGetAnonLNURL(user *lnbits.User) (string, error) {
}
// lnurlReceiveHandler outputs the LNURL of the user
func (bot TipBot) lnurlReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
func (bot *TipBot) lnurlReceiveHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
fromUser := LoadUser(ctx)
lnurlEncode, err := UserGetLNURL(fromUser)
@@ -176,7 +178,7 @@ func (bot TipBot) lnurlReceiveHandler(ctx intercept.Context) (intercept.Context,
}
// 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
@@ -207,12 +209,12 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
return "", nil,
fmt.Errorf("invalid bech32-encoded lnurl: " + rawlnurl)
}
rawurl, err = lnurl.LNURLDecode(lnurl_str)
rawurl, err = lnurl.LNURLDecodeStrict(lnurl_str)
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 +238,7 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
// return rawurl, nil, err
// }
client, err := network.GetClient(network.ClientTypeClearNet)
client, err := network.GetClientForScheme(parsed)
if err != nil {
return "", nil, err
}
@@ -273,6 +275,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
}
+194
View File
@@ -0,0 +1,194 @@
package telegram
import (
"context"
"fmt"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/nip19"
log "github.com/sirupsen/logrus"
)
var (
nosterRegisterMessage = "📖 Add your nostr pubkey for zap receipts"
nostrInfoMessage = "💜 *Your nostr information*\n\nYour pubkey: `%s`"
nostrInfoLNAddrMessage = "Your Lightning address: `%s`"
nostrHelpMessage = "⚙️ *Nostr commands:*\n`/nostr add <pubkey>` ✅ Add your nostr pubkey.\n`/nostr help` 📖 Show help."
nostrAddedMessage = "✅ *Nostr pubkey added.*"
nostrPrivateKeyErrorMessage = "🚫 This is not your public key but your private key! Very dangerous! Try again with your npub..."
nostrPublicKeyErrorMessage = "🚫 There was an error decoding your public key."
)
func uniqueSlice(slice []string) []string {
keys := make(map[string]bool)
list := []string{}
for _, entry := range slice {
if _, value := keys[entry]; !value {
keys[entry] = true
list = append(list, entry)
}
}
return list
}
func cleanUrls(slice []string) []string {
list := []string{}
for _, entry := range slice {
if strings.HasSuffix(entry, "/") {
entry = entry[:len(entry)-1]
}
list = append(list, entry)
}
return list
}
func (bot *TipBot) publishNostrEvent(ev nostr.Event, relays []string) {
pk := internal.Configuration.Nostr.PrivateKey
// // BEGIN: testing
// pub, _ := nostr.GetPublicKey(pk)
// ev = nostr.Event{
// PubKey: pub,
// CreatedAt: time.Now(),
// Kind: 1,
// Tags: nil,
// Content: "Hello World!",
// }
// // END: testing
// calling Sign sets the event ID field and the event Sig field
ev.Sign(pk)
log.Debugf("[NOSTR] 🟣 publishing nostr event %s", ev.ID)
// more relays
relays = append(relays, "wss://relay.nostr.ch", "wss://eden.nostr.land", "wss://nostr.btcmp.com", "wss://nostr.relayer.se", "wss://relay.current.fyi", "wss://nos.lol", "wss://nostr.mom", "wss://relay.nostr.info", "wss://nostr.zebedee.cloud", "wss://nostr-pub.wellorder.net", "wss://relay.snort.social/", "wss://relay.damus.io/", "wss://nostr.oxtr.dev/", "wss://nostr.fmt.wiz.biz/", "wss://brb.io")
// remove trailing /
relays = cleanUrls(relays)
// unique relays
relays = uniqueSlice(relays)
// crop relays
var max_relays int = 50
if len(relays) > max_relays {
relays = relays[:max_relays]
}
// publish the event to relays
for _, url := range relays {
go func(url string) {
// remove trailing /
relay, e := nostr.RelayConnect(context.Background(), url)
if e != nil {
log.Errorf(e.Error())
return
}
time.Sleep(3 * time.Second)
status := relay.Publish(context.Background(), ev)
log.Debugf("[NOSTR] published to %s: %s", url, status)
time.Sleep(3 * time.Second)
relay.Close()
}(url)
}
}
func (bot *TipBot) nostrHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
splits := strings.Split(m.Text, " ")
if len(splits) == 1 {
return bot.getNostrHandler(ctx)
} else if len(splits) > 1 {
switch strings.ToLower(splits[1]) {
case "add":
return bot.addNostrPubkeyHandler(ctx)
case "help":
return bot.nostrHelpHandler(ctx)
}
}
return ctx, nil
}
func (bot *TipBot) addNostrPubkeyHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
splits := strings.Split(m.Text, " ")
splitlen := len(splits)
if splitlen < 3 {
return ctx, fmt.Errorf("not enough arguments")
}
nostrKeyInput := splits[2]
// parse input
if strings.HasPrefix(nostrKeyInput, "nsec") {
bot.trySendMessage(ctx.Message().Sender, nostrPrivateKeyErrorMessage)
return ctx, fmt.Errorf("user entered nostr private key")
}
// conver to hex
if strings.HasPrefix(nostrKeyInput, "npub") {
prefix, pubkey, err := nip19.Decode(nostrKeyInput)
if err != nil {
bot.trySendMessage(ctx.Message().Sender, nostrPublicKeyErrorMessage)
return ctx, fmt.Errorf("shouldn't error: %s", err)
}
if prefix != "npub" {
bot.trySendMessage(ctx.Message().Sender, nostrPublicKeyErrorMessage)
return ctx, fmt.Errorf("returned invalid prefix")
}
nostrKeyInput = pubkey.(string)
}
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
if err != nil {
return ctx, err
}
// save node in db
user.Settings.Nostr.PubKey = nostrKeyInput
err = UpdateUserRecord(user, *bot)
if err != nil {
log.Errorf("[registerNodeHandler] could not update record of user %s: %v", GetUserStr(user.Telegram), err)
return ctx, err
}
bot.trySendMessage(ctx.Message().Sender, nostrAddedMessage)
return ctx, nil
}
func (bot *TipBot) nostrHelpHandler(ctx intercept.Context) (intercept.Context, error) {
bot.trySendMessage(ctx.Message().Sender, nosterRegisterMessage+"\n\n"+nostrHelpMessage)
return ctx, nil
}
func (bot *TipBot) getNostrHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
if err != nil {
log.Infof("Could not get user settings for user %s", GetUserStr(user.Telegram))
return ctx, err
}
var dynamicHelpMessage string
dynamicHelpMessage += nostrHelpMessage
if user.Settings.Nostr.PubKey == "" {
bot.trySendMessage(m.Sender, dynamicHelpMessage)
return ctx, fmt.Errorf("no nostr pubkey registered")
} else if len(user.Settings.Nostr.PubKey) > 0 {
pubkeyBech32, err := nip19.EncodePublicKey(user.Settings.Nostr.PubKey)
if err != nil {
log.Infof("Could not decode user nostr pubkey %s", GetUserStr(user.Telegram))
return ctx, err
}
dynamicHelpMessage += "\n\n" + fmt.Sprintf(nostrInfoMessage, pubkeyBech32)
if lnaddr, _ := bot.UserGetLightningAddress(user); len(lnaddr) > 0 {
dynamicHelpMessage += "\n\n" + fmt.Sprintf(nostrInfoLNAddrMessage, lnaddr)
}
bot.trySendMessage(m.Sender, dynamicHelpMessage)
}
return ctx, nil
}
+34 -14
View File
@@ -3,9 +3,10 @@ package telegram
import (
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
@@ -16,6 +17,7 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/str"
lnurl "github.com/fiatjaf/go-lnurl"
decodepay "github.com/fiatjaf/ln-decodepay"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
@@ -37,15 +39,16 @@ func helpPayInvoiceUsage(ctx context.Context, errormsg string) string {
type PayData struct {
*storage.Base
From *lnbits.User `json:"from"`
Invoice string `json:"invoice"`
Hash string `json:"hash"`
Proof string `json:"proof"`
Memo string `json:"memo"`
Message string `json:"message"`
Amount int64 `json:"amount"`
LanguageCode string `json:"languagecode"`
TelegramMessage *tb.Message `json:"telegrammessage"`
From *lnbits.User `json:"from"`
Invoice string `json:"invoice"`
Hash string `json:"hash"`
Proof string `json:"proof"`
Memo string `json:"memo"`
Message string `json:"message"`
Amount int64 `json:"amount"`
LanguageCode string `json:"languagecode"`
SuccessAction *lnurl.SuccessAction `json:"successAction"`
TelegramMessage *tb.Message `json:"telegrammessage"`
}
// payHandler invoked on "/pay lnbc..." command
@@ -131,6 +134,12 @@ func (bot *TipBot) payHandler(ctx intercept.Context) (intercept.Context, error)
cancelButton),
)
payMessage := bot.trySendMessageEditable(ctx.Chat(), confirmText, paymentConfirmationMenu)
// read successaction
sa, ok := ctx.Value("SuccessAction").(*lnurl.SuccessAction)
if !ok {
sa = &lnurl.SuccessAction{}
}
payData := &PayData{
Base: storage.New(storage.ID(id)),
From: user,
@@ -139,6 +148,7 @@ func (bot *TipBot) payHandler(ctx intercept.Context) (intercept.Context, error)
Memo: bolt11.Description,
Message: confirmText,
LanguageCode: ctx.Value("publicLanguageCode").(string),
SuccessAction: sa,
TelegramMessage: payMessage,
}
// add result to persistent struct
@@ -182,8 +192,6 @@ func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context,
return ctx, errors.Create(errors.UserNoWalletError)
}
invoiceString := payData.Invoice
// reset state immediately
ResetUserState(user, bot)
@@ -195,14 +203,14 @@ func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context,
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)
// pay invoice
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoiceString}, bot.Client)
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: payData.Invoice}, 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"))
@@ -235,6 +243,18 @@ func (bot *TipBot) confirmPayHandler(ctx intercept.Context) (intercept.Context,
bot.trySendMessage(ctx.Sender(), i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
bot.tryEditMessage(ctx.Message(), fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePublicPaidMessage"), userStr), &tb.ReplyMarkup{})
}
// display LNURL success action if present
sa := payData.SuccessAction
if sa.Tag == "message" && len(sa.Message) > 0 {
bot.trySendMessage(ctx.Sender(), fmt.Sprintf("✉️: `%s`", sa.Message))
} else if sa.Tag == "url" && len(sa.URL) > 0 {
bot.trySendMessage(ctx.Sender(), fmt.Sprintf("🔗: %s", str.MarkdownEscape(sa.URL)), tb.NoPreview)
if len(sa.Description) > 0 {
bot.trySendMessage(ctx.Sender(), fmt.Sprintf("✉️: %s", sa.Description))
}
}
log.Infof("[⚡️ pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
return ctx, nil
}
+2 -1
View File
@@ -4,11 +4,12 @@ import (
"bytes"
"encoding/json"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"image"
"image/jpeg"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
+3 -3
View File
@@ -250,7 +250,7 @@ func (bot *TipBot) invHandler(ctx intercept.Context) (intercept.Context, error)
var amount int64
if amount_str, err := getArgumentFromCommand(m.Text, 2); err == nil {
amount, err = getAmount(amount_str)
amount, err = GetAmount(amount_str)
if err != nil {
return ctx, err
}
@@ -424,14 +424,14 @@ func (bot *TipBot) satdressProxyHandler(ctx intercept.Context) (intercept.Contex
var amount int64
if amount_str, err := getArgumentFromCommand(m.Text, 2); err == nil {
amount, err = getAmount(amount_str)
amount, err = GetAmount(amount_str)
if err != nil {
return ctx, err
}
}
memo := "🔀 Payment proxy in."
invoice, err := bot.createInvoiceWithEvent(ctx, user, amount, memo, InvoiceCallbackSatdressProxy, "")
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"))
+17 -6
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"regexp"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
@@ -75,23 +76,33 @@ func (bot *TipBot) sendHandler(ctx intercept.Context) (intercept.Context, error)
}
// if ok, errstr := bot.SendCheckSyntax(ctx, m); !ok {
// bot.trySendMessage(m.Sender, helpSendUsage(ctx, errstr))
// NewMessage(m, WithDuration(0, bot))
// return
// }
if ok, errstr := bot.SendCheckSyntax(ctx, ctx.Message()); !ok {
bot.trySendMessage(ctx.Message().Sender, helpSendUsage(ctx, errstr))
NewMessage(ctx.Message(), WithDuration(0, bot))
return ctx, errors.Create(errors.InvalidSyntaxError)
}
// get send amount, returns 0 if no amount is given
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
if err != nil {
return ctx, err
}
// CHECK whether first or second argument is a LIGHTNING ADDRESS
arg := ""
space := regexp.MustCompile(`\s+`)
ctx.Message().Text = space.ReplaceAllString(ctx.Message().Text, " ")
if len(strings.Split(ctx.Message().Text, " ")) > 2 {
arg, err = getArgumentFromCommand(ctx.Message().Text, 2)
if err != nil {
return ctx, err
}
} else if len(strings.Split(ctx.Message().Text, " ")) == 2 {
arg, err = getArgumentFromCommand(ctx.Message().Text, 1)
if err != nil {
return ctx, err
}
}
if err == nil {
if lightning.IsLightningAddress(arg) {
+68
View File
@@ -0,0 +1,68 @@
package telegram
import (
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
)
var (
settingsHelpMessage = "📖 Change user settings\n\n`/set unit <BTC|USD|EUR|GBP>` 💶 Change your default currency."
)
func (bot *TipBot) settingHandler(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
splits := strings.Split(m.Text, " ")
if len(splits) == 1 {
bot.trySendMessage(m.Sender, settingsHelpMessage)
} else if len(splits) > 1 {
switch strings.ToLower(splits[1]) {
case "unit":
return bot.addFiatCurrency(ctx)
case "help":
return bot.nostrHelpHandler(ctx)
}
}
return ctx, nil
}
func (bot *TipBot) addFiatCurrency(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user, err := GetLnbitsUserWithSettings(m.Sender, *bot)
if err != nil {
return ctx, err
}
splits := strings.Split(m.Text, " ")
splitlen := len(splits)
if splitlen < 3 {
// display users current fiat currency
currentCurrency := strings.ToUpper(user.Settings.Display.DisplayCurrency)
if currentCurrency == "" {
currentCurrency = "BTC"
}
bot.trySendMessage(ctx.Message().Sender, fmt.Sprintf("🌍 Your current default currency is `%s`", currentCurrency))
return ctx, nil
}
currencyInput := splits[2]
// convert to lowercase and check if in [usd, eur, gbp, btc, sat]
currencyInput = strings.ToLower(currencyInput)
if currencyInput != "usd" && currencyInput != "eur" && currencyInput != "gbp" && currencyInput != "btc" && currencyInput != "sat" {
bot.trySendMessage(ctx.Message().Sender, "🚫 Invalid currency. Please use one of the following: `BTC`, `USD`, `EUR`")
return ctx, fmt.Errorf("invalid currency")
}
if currencyInput == "sat" {
currencyInput = "BTC"
}
// save node in db
user.Settings.Display.DisplayCurrency = currencyInput
err = UpdateUserRecord(user, *bot)
if err != nil {
log.Errorf("[registerNodeHandler] could not update record of user %s: %v", GetUserStr(user.Telegram), err)
return ctx, err
}
bot.trySendMessage(ctx.Message().Sender, "✅ Your default currency has been updated.")
return ctx, nil
}
+2 -8
View File
@@ -166,7 +166,7 @@ func (bot *TipBot) enterShopItemPriceHandler(ctx intercept.Context) (intercept.C
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())
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
@@ -175,10 +175,6 @@ func (bot *TipBot) enterShopItemPriceHandler(ctx intercept.Context) (intercept.C
}
}
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
runtime.IgnoreError(shop.Set(shop, bot.ShopBunt))
@@ -757,7 +753,7 @@ func (bot *TipBot) addItemFileHandler(ctx intercept.Context) (intercept.Context,
// // start a ticker to check if the user has sent more files
// if t, ok := fileStateResetTicker.Get(shop.ID); ok {
// // state reset ticker found. resetting ticker.
// t.(*runtime.ResettableFunctionTicker).ResetChan <- struct{}{}
// t.(*runtime.ResettableFunction).ResetChan <- struct{}{}
// } else {
// // state reset ticker not found. creating new one.
// ticker := runtime.NewResettableFunctionTicker(runtime.WithDuration(time.Second * 5))
@@ -951,7 +947,6 @@ func (bot *TipBot) sendFileByID(ctx context.Context, to tb.Recipient, fileId str
var ShopsText = ""
var ShopsTextWelcome = "*You are browsing %s shop.*"
var ShopsTextShopCount = "*Browse %d shops:*"
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
@@ -1061,7 +1056,6 @@ func (bot *TipBot) shopsHandler(ctx intercept.Context) (intercept.Context, error
if len(shops.Shops) > 0 {
ShopsText += fmt.Sprintf("%s\n", shopTitles)
}
ShopsText += fmt.Sprintf("\n%s", ShopsTextHelp)
// fmt.Sprintf(ShopsText, shopOwnerText, len(shops.Shops), shopTitles)
+3 -2
View File
@@ -2,6 +2,8 @@ package telegram
import (
"fmt"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
@@ -10,7 +12,6 @@ import (
"github.com/eko/gocache/store"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v3"
"time"
)
func (bot TipBot) shopsMainMenu(ctx intercept.Context, shops *Shops) *tb.ReplyMarkup {
@@ -203,7 +204,7 @@ func (bot *TipBot) sendStatusMessageAndDelete(ctx intercept.Context, to tb.Recip
id := fmt.Sprintf("shopview-delete-%d", user.Telegram.ID)
statusMsg := bot.sendStatusMessage(ctx, to, what, options...)
// kick off ticker to remove all messages
ticker := runtime.GetTicker(id, runtime.WithDuration(5*time.Second))
ticker := runtime.GetFunction(id, runtime.WithTicker(time.NewTicker(5*time.Second)), runtime.WithDuration(5*time.Second))
if !ticker.Started {
ticker.Do(func() {
bot.shopViewDeleteAllStatusMsgs(ctx, user)
+2 -1
View File
@@ -4,10 +4,11 @@ import (
"context"
stderrors "errors"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"strconv"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal"
+1
View File
@@ -20,5 +20,6 @@ func initializeStateCallbackMessage(bot *TipBot) {
lnbits.UserStateShopItemSendTitle: bot.enterShopItemTitleHandler,
lnbits.UserStateShopItemSendItemFile: bot.addItemFileHandler,
lnbits.UserEnterShopsDescription: bot.enterShopsDescriptionHandler,
lnbits.UserEnterDallePrompt: bot.confirmGenerateImages,
}
}
+2 -1
View File
@@ -4,9 +4,10 @@ import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
+244
View File
@@ -0,0 +1,244 @@
package telegram
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
log "github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode"
"github.com/tidwall/buntdb"
tb "gopkg.in/lightningtipbot/telebot.v3"
)
var defaultTicketDuration = time.Minute * 15
// handleTelegramNewMember is invoked when users join groups.
// handler will create a new invoice and send it to the group chat.
// a ticket callback timer function is stored in the blunt db.
func (bot *TipBot) handleTelegramNewMember(ctx intercept.Context) (intercept.Context, error) {
id := strconv.FormatInt(ctx.Chat().ID, 10)
group, err := bot.loadGroup(id)
if err != nil {
return ctx, err
}
if !bot.isAdmin(ctx.Chat(), bot.Telegram.Me) {
log.Traceln("[TICKET] I am not an admin of this group")
return ctx, fmt.Errorf("no admin rights")
}
user := LoadUser(ctx)
// if the user does not have an account we put his Telegram user here
// because we will need it after the invoice callback has been triggered in stopJoinTicketTimer
if user == nil {
user = &lnbits.User{
ID: "",
Telegram: ctx.Message().Sender,
}
}
ownerUser, err := GetUser(group.Owner, *bot)
if err != nil {
log.Errorln("[TICKET] Error: no owner found")
return ctx, err
}
ticket := JoinTicket{
Sender: ctx.Sender(),
Ticket: group.Ticket,
}
// group owner creates invoice
invoice, err := ownerUser.Wallet.Invoice(
lnbits.InvoiceParams{
Out: false,
Amount: ticket.Ticket.Price,
Memo: ticket.Ticket.Memo,
Webhook: internal.Configuration.Lnbits.WebhookServer},
bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[handleTelegramNewMember] Could not create an invoice: %s", err.Error())
log.Errorln(errmsg)
return ctx, err
}
// send the owner invoice to chat
// TicketEvent is used for callback button (if user has balance)
ticketEvent := TicketEvent{
// invoice event is used for invoice callbacks (do not kick if invoice is paid)
InvoiceEvent: &InvoiceEvent{
Base: storage.New(storage.ID(fmt.Sprintf("invoice-event:%s", id))),
Invoice: &Invoice{PaymentHash: invoice.PaymentHash,
PaymentRequest: invoice.PaymentRequest,
Amount: ticket.Ticket.Price,
Memo: ticket.Ticket.Memo},
Payer: user,
Chat: ctx.Chat(),
Callback: InvoiceCallbackPayJoinTicket,
CallbackData: "",
LanguageCode: ctx.Value("publicLanguageCode").(string),
},
Group: group,
Base: storage.New(storage.ID(fmt.Sprintf("ticket-event:%s", id))),
}
captionText := fmt.Sprintf("⚠️ %s, this group requires you to pay *%d sat* to join. You have 15 minutes to pay or you will be kicked for one day.", GetUserStrMd(ctx.Message().Sender), ticket.Ticket.Price)
var balance int64 = 0
if user.ID != "" {
// if the user has an account
// // 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)
}
} else {
balance = 0
}
var msg *tb.Message
if balance >= group.Ticket.Price {
_, menu := bot.getSendPayButton(ctx, ticketEvent)
msg = bot.trySendMessageEditable(ctx.Chat(), captionText, menu)
} else {
// create qr code
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
if err != nil {
return ctx, err
}
entryMessage := &tb.Photo{
File: tb.File{FileReader: bytes.NewReader(qr)},
Caption: captionText}
entryMessage.Caption = fmt.Sprintf("%s\n\n`%s`", entryMessage.Caption, invoice.PaymentRequest)
msg = bot.trySendMessageEditable(ctx.Chat(), entryMessage)
}
ticketEvent.Message = msg
ticket.Message = msg
ticket.CreatedTimestamp = time.Now()
err = bot.Bunt.Set(&ticket)
if err != nil {
return ctx, err
}
// save invoice struct for later use
err = ticketEvent.Set(&ticketEvent, bot.Bunt)
if err != nil {
return ctx, err
}
err = ticketEvent.InvoiceEvent.Set(ticketEvent.InvoiceEvent, bot.Bunt)
if err != nil {
return ctx, err
}
bot.startTicketCallbackFunctionTimer(ticket)
fmt.Println(ctx.Message())
return ctx, nil
}
// stopTicketTimer will load the timer function based on the event.
// should stop the ticker timer function and remove ticket from bluntDB.
func (bot *TipBot) stopJoinTicketTimer(event Event) {
ev := event.(*InvoiceEvent)
ticket := JoinTicket{Sender: ev.Payer.Telegram, Message: ev.Message}
err := bot.Bunt.Get(&ticket)
if err != nil {
log.Errorf("[stopJoinTicketTimer] %v", err)
return
}
if commission := getTicketCommission(ticket.Ticket); commission > 0 {
me, err := GetUser(bot.Telegram.Me, *bot)
if err != nil {
log.Errorf("[stopJoinTicketTimer] %v", err)
return
}
invoice, err := me.Wallet.Invoice(
lnbits.InvoiceParams{
Out: false,
Amount: commission,
Memo: fmt.Sprintf("Ticket %d", ticket.Message.Chat.ID)},
bot.Client)
if err != nil {
log.Errorf("[stopJoinTicketTimer] %v", err)
return
}
_, err = ticket.Ticket.Creator.Wallet.Pay(lnbits.PaymentParams{Bolt11: invoice.PaymentRequest, Out: true}, bot.Client)
if err != nil {
log.Errorf("[stopJoinTicketTimer] %v", err)
return
}
}
d := time.Until(time.Now().Add(defaultTicketDuration))
bot.tryDeleteMessage(ev.Message)
t := runtime.GetFunction(ticket.Key(), runtime.WithDuration(d))
t.StopChan <- struct{}{}
err = bot.Bunt.Delete(ticket.Key(), &ticket)
if err != nil {
log.Errorf("[stopJoinTicketTimer] %v", err)
}
}
// startTicketCallbackFunctionTimer will start a ticket which will ban users if the timer runs out.
func (bot *TipBot) startTicketCallbackFunctionTimer(ticket JoinTicket) {
// check if ticket is already expired
if ticket.CreatedTimestamp.Add(defaultTicketDuration).Before(time.Now()) {
return
}
// ticket is valid. create duration until kick
ticketDuration := time.Until(ticket.CreatedTimestamp.Add(defaultTicketDuration))
// create function timer
t := runtime.NewResettableFunction(ticket.Key(),
runtime.WithTimer(time.NewTimer(ticketDuration)))
// run the ticket callback function
t.Do(func() {
// ticket expired
member, err := bot.Telegram.ChatMemberOf(ticket.Message.Chat, ticket.Sender)
if err != nil {
log.Errorln("🧨 could not fetch / ban chat member")
return
}
// ban user
err = bot.Telegram.Ban(ticket.Message.Chat, member)
if err != nil {
log.Errorln(err)
}
err = bot.Bunt.Delete(ticket.Key(), &ticket)
if err != nil {
log.Errorln(err)
}
bot.tryDeleteMessage(ticket.Message)
})
}
// restartPersistedTickets kicks of all ticket timers
func (bot *TipBot) restartPersistedTickets() {
bot.Bunt.View(func(tx *buntdb.Tx) error {
err := tx.Ascend("join-ticket", func(key, value string) bool {
ticket := JoinTicket{}
err := json.Unmarshal([]byte(value), &ticket)
if err != nil {
return true
}
bot.startTicketCallbackFunctionTimer(ticket)
return true // continue iteration
})
return err
})
}
func getTicketCommission(ticket *Ticket) int64 {
if ticket.Price < 20 {
return 0
}
// 2% cut + 100 sat base fee
commissionSat := ticket.Price*ticket.Cut/100 + ticket.BaseFee
if ticket.Price <= 1000 {
// if < 1000, then 10% cut + 10 sat base fee
commissionSat = ticket.Price*ticket.CutCheap/100 + ticket.BaseFeeCheap
}
return commissionSat
}
+1 -1
View File
@@ -58,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)
}
+20 -20
View File
@@ -11,26 +11,26 @@ import (
)
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)
+21 -4
View File
@@ -10,6 +10,7 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/api/userpage"
"github.com/LightningTipBot/LightningTipBot/internal/lndhub"
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
"github.com/LightningTipBot/LightningTipBot/internal/nostr"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
_ "net/http/pprof"
@@ -54,23 +55,39 @@ func startApiServer(bot *telegram.TipBot) {
// append lnurl ctx functions
lnUrl := lnurl.New(bot)
s.AppendRoute("/.well-known/lnurlp/{username}", lnUrl.Handle, http.MethodGet)
// userpage server
userpage := userpage.New(bot)
s.AppendRoute("/@{username}", userpage.UserPageHandler, http.MethodGet)
s.AppendRoute("/app/@{username}", userpage.UserWebAppHandler, http.MethodGet)
// nostr nip05 identifier
nostr := nostr.New(bot)
s.AppendRoute("/.well-known/nostr.json", nostr.Handle, http.MethodGet)
// 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)
}
+405
View File
@@ -0,0 +1,405 @@
# COMMANDS
helpCommandStr = """pomoc"""
basicsCommandStr = """základy"""
tipCommandStr = """tip"""
balanceCommandStr = """zůstatek"""
sendCommandStr = """poslat"""
invoiceCommandStr = """invoice"""
payCommandStr = """zaplatit"""
donateCommandStr = """podpořit"""
advancedCommandStr = """pokročilé"""
transactionsCommandStr = """transakce"""
logCommandStr = """log"""
listCommandStr = """list"""
linkCommandStr = """odkaz"""
lnurlCommandStr = """LNURL"""
faucetCommandStr = """faucet"""
tipjarCommandStr = """tipjar"""
receiveCommandStr = """přijmout"""
hideCommandStr = """skrýt"""
volcanoCommandStr = """sopka"""
showCommandStr = """ukázat"""
optionsCommandStr = """možnosti"""
settingsCommandStr = """nastavení"""
saveCommandStr = """uložit"""
deleteCommandStr = """smazat"""
infoCommandStr = """info"""
# NOTIFICATIONS
cantDoThatMessage = """To nelze udělat."""
cantClickMessage = """Toto tlačítko nejde zmáčkout."""
balanceTooLowMessage = """Tvůj zůstatek je příliš malý."""
# BUTTONS
sendButtonMessage = """✅ Odeslat"""
payButtonMessage = """✅ Zaplatit"""
payReceiveButtonMessage = """💸 Zaplatit"""
receiveButtonMessage = """✅ Přijmout"""
withdrawButtonMessage = """✅ Vybrat"""
cancelButtonMessage = """🚫 Zrušit"""
collectButtonMessage = """✅ Vybrat"""
nextButtonMessage = """Dále"""
backButtonMessage = """Zpět"""
acceptButtonMessage = """Potvrdit"""
denyButtonMessage = """Odmítnout"""
tipButtonMessage = """Platba"""
revealButtonMessage = """Odhalit"""
showButtonMessage = """Ukázat"""
hideButtonMessage = """Skrýt"""
joinButtonMessage = """Připojit se"""
optionsButtonMessage = """Možnosti"""
settingsButtonMessage = """Nastavení"""
saveButtonMessage = """Uložit"""
deleteButtonMessage = """Smazat"""
infoButtonMessage = """Info"""
cancelButtonEmoji = """🚫"""
payButtonEmoji = """💸"""
# HELP
helpMessage = """⚡️ *Peněženka*
_Tento bot je bitcoinová lightning peněženka, která umožňuje posílat platby na Telegramu. Pro použití přidejte bota do chatu. Základní jednotkou je 1 sat. 100 000 000 sats = 1 bitcoin. Napiš 📚 /basics pro víc info._
❤️ *Podpořit*
_Tento bot si neúčtuje žádné poplatky, ale jeho provoz stojí nějaké sats. Pokud se Ti líbí, zvaž prosím podporu tohoto projektu. Pro podporu napiš_ `/donate 1000`
%s
⚙️ *Příkazy*
*/tip* 🏅 Odpověz na zprávu, abys poslal tip: `/tip <částka> [<zpráva>]`
*/balance* 👑 Zkontroluj svůj zůstatek: `/balance`
*/send* 💸 Poslat platbu uživateli: `/send <částka> @uživatel nebo uživatel@ln.tips [<zpráva>]`
*/invoice* ⚡️ Vytvořit lightning (invoice): `/invoice <částka> [<zpráva>]`
*/pay* ⚡️ Zaplatit lightning invoice: `/pay <invoice>`
*/donate* ❤️ Podpořit projekt: `/donate 1000`
*/advanced* 🤖 Pokročilé funkce.
*/help* 📖 Tato nápověda."""
infoHelpMessage = """ℹ️ *Info*"""
infoYourLightningAddress = """Tvoje lightning adresa je `%s`"""
basicsMessage = """🧡 *Bitcoin*
_Bitcoin jsou internetové peníze. Jsou decentralizované, k jejich použití nepotřebuješ povolení a nemají žádnou centrální autoritu, která by je řídila. Bitcoin jsou zdravé peníze, které jsou na rozdíl od starého finančního systému rychlejší, bezpečnější a pro každého._
🧮 *Ekonomnika*
_Nejmenší jednotkou bitcoinu je 1 sat. 100 000 000 sats = 1 bitcoin. Nikdy nebude existovat víc než 21 milionů bitcoinů. Kurz bitcoinu vůči státním měnám se může často a náhle měnit. Nicméně, pokud žijete na bitcoinovém standardu, 1 sat se bude pořád rovnat 1 satu._
⚡️ *Lightning Network*
_Lightningová síť je platební protokol který umožňuje rychlé a levné bitcoinové platby nevyžadující téměř žádnou energii. Tato síť škáluje bitcoin pro miliardy lidí na celém světě._
📲 *Lightning peněženky*
_Tvoje prostředky z této lightning peněženky můžeš poslat na jakoukoliv jinou a naopak. Doporučené lightning peněženky pro mobil jsou_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (držíte své klíče), nebo_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(jednoduchá, ale klíče od sats nedržíte)_.
📄 *Open Source*
_Tento bot je volný a otevřený_ [open source](https://github.com/LightningTipBot/LightningTipBot) _software. Můžeš ho běžet na vlastním počítači a používat jej ve vlastní komunitě._
✈️ *Telegram*
_Přidej tohoto bota do své skupiny na Telegramu a můžeš posílat /tip za zprávy. Pokud uděláš bota adminem skupiny, bude odstraňovat příkazy, aby zůstal chat přehlednější._
🏛 *Podmínky*
_Nejsme správci Tvých prostředků. Budeme konat v Tvém nejlepším zájmu, ale také jsme si vědomi nejisté situace bez KYC, dokud nepřijdeme na něco jiného. Jakákoli částka, kterou si pošleš do peněženky, je proto považována za příspěvek podpory. Neposílej nám všechny svoje peníze. Vezmi v potaz, že bot je v beta fázi vývoje. Používáš ho na vlastní riziko._
❤️ *Podpora*
_Tento bot si neúčtuje žádné poplatky, ale jeho provoz stojí nějaké sats. Pokud se Ti líbí, zvaž prosím podporu tohoto projektu. Pro podporu napiš_ `/donate 1000`"""
helpNoUsernameMessage = """👋 Prosím, nastav si uživatelské jméno na Telegramu."""
advancedMessage = """%s
👉 *Inline příkazy*
*send* 💸 Poslat sats do chatu: `%s send <částka> [<uživatel>] [<zpráva>]`
*receive* 🏅 Vyžádat platbu: `... receive <částka> [<uživatel>] [<zpráva>]`
*faucet* 🚰 Vytvořit faucet: `... faucet <kapacita> <částka_na_uživatele> [<zpráva>]`
*tipjar* 🍯 Vytvořit tipjar: `... tipjar <kapacita> <částka_na_uživatele> [<zpráva>]`
📖 V každém chatu můžeš používat inline příkazy, dokonce i v soukromých konverzacích. Po zadání inline příkazu chvilku vyčkej a *klikni* na výsledek, nemačkej enter.
⚙️ *Pokročilé příkazy*
*/transactions* 📊 Seznam transakcí
*/link* 🔗 Propojit peněženku s [BlueWallet](https://bluewallet.io/) nebo [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ LNURL obdržet nebo zaplatit: `/lnurl` nebo `/lnurl <lnurl> [memo]`
*/nostr* 💜 Connect to Nostr: `/nostr`
*/faucet* 🚰 Vytvořit faucet: `/faucet <kapacita> <částka_na_uživatele>`
*/tipjar* 🍯 Vytvořit tipjar: `/tipjar <kapacita> <částka_na_uživatele>`
*/group* 🎟 Vytvořit vstupenky do skupiny: `/group add <název_skupiny> [<cena_vstupenky>]`
*/shop* 🛍 Prohlížet obchody: `/shop` nebo `/shop <uživatel/id_obchodu>`
*/generate* 🎆 Vytvořit obrázky od DALLE 2: `/generate <prompt>`"""
# GENERIC
enterAmountRangeMessage = """💯 Zadej částku mezi %d a %d sats."""
enterAmountMessage = """💯 Zadej částku."""
enterUserMessage = """👤 Zadej uživatele."""
enterTextMessage = """⌨️ Zadej text."""
errorReasonMessage = """🚫 Chyba: %s"""
# START
startSettingWalletMessage = """🧮 Nastavování peněženky..."""
startWalletCreatedMessage = """🧮 Peněženka vytvořena."""
startWalletReadyMessage = """✅ *Tvá peněženka je připravena.*"""
startWalletErrorMessage = """🚫 Chyba při vytváření peněženky. Zkus to později znovu."""
startNoUsernameMessage = """☝️ Vypadá to, že na Telegramu nemáš ještě uživatelské jméno (@username). Nevadí, pro používání tohoto bota ho nepotřebuješ. Nicméně, pro snazší používání peněženky si nastav uživatelské jméno v nastavení Telegramu. Poté zadej příkaz /balance a bot si zaktualizuje své záznamy."""
# BALANCE
balanceMessage = """👑 *Tvůj zůstatek:* %d sat"""
balanceErrorMessage = """🚫 Nepodařilo se získat info o zůstatku. Zkus to později znovu."""
# TIP
tipDidYouReplyMessage = """Odpověděl jsi na zprávu kvůli platbě? Pro odpověď na jakoukoli zprávu na PC klikni pravým myšítkem a vyber ´Odpovědět´ nebo na mobilu přes zprávu přejeď do strany. Pokud chceš poslat platbu jinému uživateli přímo, použij příkaz /send"""
tipInviteGroupMessage = """ℹ️ Tohoto bota můžeš přizvat do jakékoli skupiny a posílat v ní platby."""
tipEnterAmountMessage = """Zadal jsi částku?"""
tipValidAmountMessage = """Zadal jsi platnou částku?"""
tipYourselfMessage = """📖 Nemůžeš poslat platbu sobě."""
tipSentMessage = """💸 %d sats posláno pro %s."""
tipReceivedMessage = """🏅 %s ti poslal %d sats."""
tipErrorMessage = """🚫 Platba selhala."""
tipUndefinedErrorMsg = """Prosím, zkus to později znovu."""
tipHelpText = """📖 Ou, tohle se nezdařilo. %s
*Použití:* `/tip <částka> [<zpráva>]`
*Příklad:* `/tip 1000 Díky moc!`"""
# SEND
sendValidAmountMessage = """Zadal jsi platnou částku?"""
sendUserHasNoWalletMessage = """🚫 Uživatel %s si ještě nevytvořil peněženku."""
sendSentMessage = """💸 %d sats posláno uživateli %s."""
sendPublicSentMessage = """💸 %d sats posláno od %s uživateli %s."""
sendReceivedMessage = """🏅 %s ti poslal %d sats."""
sendErrorMessage = """🚫 Odeslání selhalo."""
confirmSendMessage = """Chceš zaplatit uživateli %s?\n\n💸 Částka: %d sats"""
confirmSendAppendMemo = """\n✉️ %s"""
sendCancelledMessage = """🚫 Odeslání zrušeno."""
errorTryLaterMessage = """🚫 Chyba. Prosím, zkus to později znovu."""
sendSyntaxErrorMessage = """Zadal jsi částku a příjemce? Můžeš použít příkaz /send k poslání platby buď uživateli Telegramu jako %s nebo na lightning adresu jako LightningTipBot@ln.tips."""
sendHelpText = """📖 Ou, tohle se nezdařilo. %s
*Použití:* `/send <částka> <uživatel> [<zpráva>]`
*Příklad:* `/send 1000 @LightningTipBot Všichni jsme Satoshi ❤️`
*Příklad:* `/send 1234 LightningTipBot@ln.tips`"""
# INVOICE
invoiceReceivedMessage = """⚡️ Obdržel jsi %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Obdržel jsi %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Zadal jsi částku?"""
invoiceValidAmountMessage = """Zadal jsi platnou částku?"""
invoiceHelpText = """📖 Ou, tohle se nezdařilo. %s
*Použití:* `/invoice <částka> [<zpráva>]`
*Příklad:* `/invoice 1000 Děkuji!`"""
invoicePaidText = """✅ Invoice zaplacena."""
# PAY
paymentCancelledMessage = """🚫 Platba zrušena."""
invoicePaidMessage = """⚡️ Platba odeslána."""
invoicePublicPaidMessage = """⚡️ Platba od %s odeslána."""
invalidInvoiceHelpMessage = """Máš platnou lightning invoice? Zkus příkaz /send k poslání platby uživateli Telegramu nebo na lightning adresu."""
invoiceNoAmountMessage = """🚫 Nemůžu zaplatit invoice bez částky."""
insufficientFundsMessage = """🚫 Nedostatek prostředků. Máš %d sats, ale potřebuješ alespoň %d sats."""
feeReserveMessage = """⚠️ Odeslání celého zůstatku se nemusí zdařit kvůli poplatkům v síti. Nechej rezervu aspoň 1% na poplatky."""
invoicePaymentFailedMessage = """🚫 Platba selhala: %s"""
invoiceUndefinedErrorMessage = """Nemohl jsem zaplatit invoice."""
confirmPayInvoiceMessage = """Chceš poslat tuto platbu?\n\n💸 Částka: %d sats"""
confirmPayAppendMemo = """\n✉️ %s"""
payHelpText = """📖 Ou, tohle se nezdařilo. %s
*Použití:* `/pay <invoice>`
*Příklad:* `/pay lnbc20n1psscehd...`"""
# DONATE
donationSuccess = """🙏 Díky za tvůj příspěvek."""
donationErrorMessage = """🚫 Ale ne, odeslání přspěvku selhalo."""
donationProgressMessage = """🧮 Příprava odeslání příspěvku..."""
donationFailedMessage = """🚫 Příspěvek selhal: %s"""
donateEnterAmountMessage = """Zadal jsi částku?"""
donateValidAmountMessage = """Zadal jsi platnou částku?"""
donateHelpText = """📖 Ou, tohle se nezdařilo. %s
*Použití:* `/donate <částka>`
*Příklad:* `/donate 1000`"""
# PHOTO
photoQrNotRecognizedMessage = """🚫 Lightning invoice nebo LNURL nešlo rozpoznat. Pokus se QR kód vycentrovat, oříznout, nebo ho více přiblížit."""
photoQrRecognizedMessage = """✅ QR kód:
`%s`"""
# LNURL
lnurlReceiveInfoText = """👇 Pro příjem plateb můžeš používat tuto statickou LNURL."""
lnurlResolvingUrlMessage = """🧮 Zpracovávám adresu..."""
lnurlGettingUserMessage = """🧮 Připravuji platbu..."""
lnurlPaymentFailed = """🚫 Platba selhala: %s"""
lnurlInvalidAmountMessage = """🚫 Neplatná částka."""
lnurlInvalidAmountRangeMessage = """🚫 Částka musí být mezi %d a %d sats."""
lnurlNoUsernameMessage = """🚫 Pro příjem plateb pomocí LNURL potřebuješ na Telegramu uživatelské jméno."""
lnurlHelpText = """📖 Ou, tohle se nezdařilo. %s
*Použití:* `/lnurl [částka] <lnurl>`
*Příklad:* `/lnurl LNURL1DP68GUR...`"""
# LNURL LOGIN
confirmLnurlAuthMessager = """Chceš se přihlásit do %s?"""
lnurlSuccessfulLogin = """✅ Přihlášení úspěšné."""
loginButtonMessage = """✅ Přihlásit"""
loginCancelledMessage = """🚫 Přihlášení zrušeno."""
# LNURL WITHDRAW
confirmLnurlWithdrawMessage = """Chceš provést tento výběr?\n\n💸 Částka: %d sats"""
lnurlPreparingWithdraw = """🧮 Příprava výběru..."""
lnurlWithdrawFailed = """🚫 Výběr selhal."""
lnurlWithdrawCancelled = """🚫 Výběr zrušen."""
lnurlWithdrawSuccess = """✅ Výběr vyžádán."""
# LINK
walletConnectMessage = """🔗 *Propojit vlastní peněženku*
⚠️ Nikdy s nikým nesdílej URL nebo QR kód, jinak bude mít přístup k tvým prostředkům. Použij příkaz /api pro své API klíče.
- *BlueWallet:* Vyber *Nová peněženka*, *Importovat peněženku*, *Scanovat nebo importovat ze souboru* a nascanuj QR kód.
- *Zeus:* Zkopíruj URL níže, vyber *Add a new node/Přidat novou nodu*, zvol *LNDHub* jako Node interface/Rozhraní nody, vlož URL a ulož nastavení *Save Node Config*."""
couldNotLinkMessage = """🚫 Propojení s peněženkou se nezdařilo. Prosím, zkus to později znovu."""
linkHiddenMessage = """🔍 Propojení je skryto. Abys ho znovu viděl, zadej /link příkaz."""
# API
apiConnectMessage = """🔗 *Tvé API klíče*
⚠️ Nikdy s nikým tyto klíče nesdílej, jinak bude mít přístup k tvým prostředkům. Použij příkaz /link k propojení své peněženky.
- *Admin klíč:* `%s`
- *Invoice klíč:* `%s`"""
apiHiddenMessage = """🔍 Klíče jsou skryty. Abys je znovu viděl, zadej /api příkaz."""
# FAUCET
inlineQueryFaucetTitle = """🚰 Vytvořit faucet."""
inlineQueryFaucetDescription = """Použití: @%s faucet <kapacita> <částka_na_uživatele>"""
inlineResultFaucetTitle = """🚰 Vytvořit faucet s %d sats."""
inlineResultFaucetDescription = """👉 Klikni zde pro vytvoření faucetu v tomto chatu."""
inlineFaucetMessage = """Zmáčkni ✅ pro výběr %d sats z faucetu od %s.
🚰 Zbývá: %d/%d sats (rozdáno %d/%d uživatelům)
%s"""
inlineFaucetEndedMessage = """🚰 Faucet je prázdný 🍺\n\n🏅 %d sats rozdáno %d uživatelům."""
inlineFaucetAppendMemo = """\n✉️ %s"""
inlineFaucetCreateWalletMessage = """Komunikuj s %s 👈 pro správu své peněženky."""
inlineFaucetCancelledMessage = """🚫 Faucet zrušen."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Částka na uživatele musí dělit kapacitu faucetu beze zbytku nebo je příliš malá (min 5 sats)."""
inlineFaucetInvalidAmountMessage = """🚫 Neplatná částka."""
inlineFaucetSentMessage = """🚰 %d sats posláno %s."""
inlineFaucetReceivedMessage = """🚰 %s ti poslal %d sats."""
inlineFaucetHelpFaucetInGroup = """Vytvoř faucet ve skupině s botem nebo použij 👉 inline příkaz (napiš /advanced pro víc info)."""
inlineFaucetAlreadyTookMessage = """🚫 Z tohoto faucetu už jsi čerpal."""
inlineFaucetHelpText = """📖 Ou, tohle se nezdařilo. %s
*Použití:* `/faucet <kapacita> <částka_na_uživatele>`
*Příklad:* `/faucet 210 21`"""
# INLINE SEND
inlineQuerySendTitle = """💸 Poslat platbu do chatu."""
inlineQuerySendDescription = """Použití: @%s send <částka> [<uživatel>] [<zpráva>]"""
inlineResultSendTitle = """💸 Poslat %d sats."""
inlineResultSendDescription = """👉 Klikni pro poslání %d sats do tohoto chatu."""
inlineSendMessage = """Zmáčkni ✅ pro obdržení platby od %s.\n\n💸 Částka: %d sats"""
inlineSendAppendMemo = """\n✉️ %s"""
inlineSendUpdateMessageAccept = """💸 %d sats posláno od %s uživateli %s."""
inlineSendCreateWalletMessage = """Chatuj s %s 👈 pro správu své peněženky."""
sendYourselfMessage = """📖 Nemůžeš platit sám sobě."""
inlineSendFailedMessage = """🚫 Platba selhala."""
inlineSendInvalidAmountMessage = """🚫 Částka musí být větší než 0."""
inlineSendBalanceLowMessage = """🚫 Tvůj zůstatek je příliš malý."""
# INLINE RECEIVE
inlineQueryReceiveTitle = """🏅 Vyžádat platbu v chatu."""
inlineQueryReceiveDescription = """Použití: @%s receive <částka> [<uživatel>] [<zpráva>]"""
inlineResultReceiveTitle = """🏅 Dostat %d sats."""
inlineResultReceiveDescription = """👉 Klikni pro vyžádání platby %d sats."""
inlineReceiveMessage = """Zmáčkni 💸 pro zaplacení uživateli %s.\n\n💸 Částka: %d sats"""
inlineReceiveAppendMemo = """\n✉️ %s"""
inlineReceiveUpdateMessageAccept = """💸 %d sats posláno od %s uživateli %s."""
inlineReceiveCreateWalletMessage = """Chatuj s %s 👈 pro správu své peněženky."""
inlineReceiveYourselfMessage = """📖 Nemůžeš platit sám sobě."""
inlineReceiveFailedMessage = """🚫 Platba selhala."""
inlineReceiveCancelledMessage = """🚫 Platba zrušena."""
# TIPJAR
inlineQueryTipjarTitle = """🍯 Vytvořit tipjar."""
inlineQueryTipjarDescription = """Použití: @%s tipjar <kapacita> <částka_od_uživatele>"""
inlineResultTipjarTitle = """🍯 Vytvořit tipjar na %d sats."""
inlineResultTipjarDescription = """👉 Klikni zde pro vytvoření tipjar v tomto chatu."""
inlineTipjarMessage = """Zmáčkni 💸 pro *platbu %d sats* do tohoto tipjar od %s.
🙏 Věnováno: *%d*/%d sats (od %d uživatelů)
%s"""
inlineTipjarEndedMessage = """🍯 Tipjar od %s je plný ⭐️\n\n🏅 Věnováno %d sats od %d uživatelů."""
inlineTipjarAppendMemo = """\n✉️ %s"""
inlineTipjarCancelledMessage = """🚫 Tipjar zrušen."""
inlineTipjarInvalidPeruserAmountMessage = """🚫 Částka od jednoho uživatele musí dělit kapacitu tipjar beze zbytku."""
inlineTipjarInvalidAmountMessage = """🚫 Neplatná částka."""
inlineTipjarSentMessage = """🍯 %d sats posláno pro %s."""
inlineTipjarReceivedMessage = """🍯 %s ti poslal %d sats."""
inlineTipjarHelpTipjarInGroup = """Vytvoř tipjar ve skupině s botem nebo použij 👉 inline příkaz (/advanced pro víc info)."""
inlineTipjarHelpText = """📖 Ou, tohle se nezdařilo. %s
*Použití:* `/tipjar <kapacita> <částka_od_uživatele>`
*Příklad:* `/tipjar 210 21`"""
# GROUP TICKETS
groupAddGroupHelpMessage = """📖 Ou, tohle se nezdařilo. Tento příkaz funguje pouze ve skupinovém chatu. Mohou ho použít pouze vlastníci skupin.\nPoužití: `/group add <název_skupiny> [<částka>]`\nPříklad: `/group add NejvícHustáSkupina 1000`"""
groupJoinGroupHelpMessage = """📖 Ou, tohle se nezdařilo. Prosím, zkus to znovu.\nPoužití: `/join <název_skupiny>`\nPříklad: `/join NejvícHustáSkupina`"""
groupClickToJoinMessage = """🎟 [Klikni zde](%s) 👈 pro připojení `%s`."""
groupTicketIssuedGroupMessage = """🎟 Uživatel %s obdržel vstupenku do této skupiny."""
groupPayInvoiceMessage = """🎟 Pro připojení se ke skupině %s, zaplať výše uvedenou invoice."""
groupBotIsNotAdminMessage = """🚫 Ou, tohle se nezdařilo. Musíš mě jmenovat adminem a dát mi práva zvát uživatele."""
groupNameExists = """🚫 Skupina s tímto názvem už existuje. Prosím, vyber jiný název."""
groupAddedMessage = """🎟 Vstupenky pro skupinu `%s` přidány.\nAlias: `%s` Cena: %d sats\n\nPro vyžádání vstupenky do této skupiny začni soukromý chat s %s a napiš `/join %s`."""
groupNotFoundMessage = """🚫 Skupinu s tímto názvem se nepodařilo najít."""
groupReceiveTicketInvoiceCommission = """🎟 Obdržel jsi *%d sats* (bez provize %d sats) za vstupenku do skupiny `%s` od uživatele %s."""
groupReceiveTicketInvoice = """🎟 Obdržel jsi *%d sats* za vstupenku do skupiny `%s` od uživatele %s."""
commandPrivateMessage = """Prosím, použij tento příkaz v soukromém chatu s %s."""
groupHelpMessage = """🎟 Vstupenky do soukromých skupin 🎟
Prodej vstupenky do své _soukromé skupiny_ a zbavíš se spam botů.
*Pokyny pro skupinové adminy:*
1) Pozvi %s do své skupiny a udělej ho adminem.
2) Skupinu změň na soukromou.
3) Ve své skupině, jako její majitel, napiš `/group add <název_skupiny> [<cena_vstupenky>]`.
_Poplatky: Bot si bere provizi 10%% +10 sats za levné vstupenky. Je-li cena vstupenky >= 1000 sats, je provize 2%% + 100 sats._
*Pokyny pro členy skupin:*
Pro připojení ke skupině si promluv s %s a v soukromé zprávě napiš `/join <název_skupiny>`.
📖 *Použití:*
*Pro adminy (ve skupinovém chatu):* `/group add <název_skupiny> [<cena_vstupenky>]`\nPříklad: `/group add NejvícHustáSkupina 1000`
*Pro uživatele (v soukromém chatu):* `/join <název_skupiny>`\nPříklad: `/join NejvícHustáSkupina`"""
# DALLE GENERATE
generateDalleHelpMessage = """Vytvořit obrázky pomocí OpenAI DALLE 2.\nPoužití: `/generate <prompt>`\nCena: 1000 sat"""
generateDallePayInvoiceMessage = """Zaplať tuto invoice pro vytvoření 4 obrázků 👇"""
generateDalleGeneratingMessage = """Tvé obrázky se generují. Chvilku strpení..."""
+23 -7
View File
@@ -120,16 +120,20 @@ advancedMessage = """%s
⚙️ *Fortgeschrittene Befehle*
*/transactions* 📊 Liste der Transaktionen
*/link* 🔗 Verbinde dein Wallet mit [BlueWallet](https://bluewallet.io/) oder [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Lnurl empfangen oder senden: `/lnurl` oder `/lnurl <lnurl>`
*/lnurl* ⚡️ Lnurl empfangen oder senden: `/lnurl` oder `/lnurl <lnurl> [memo]`
*/nostr* 💜 Verbinde Nostr: `/nostr`
*/faucet* 🚰 Erzeuge einen Zapfhahn: `/faucet <gesamt> <pro_user>`
*/tipjar* 🍯 Erzeuge eine Spendendose: `/tipjar <gesamt> <pro_user>`
*/group* 🎟 Tickets für Gruppenchats: `/group add <meine_gruppe> [<ticket_preis>]`
*/shop* 🛍 Durchsuche shops: `/shop` oder `/shop <user/shop_id>`"""
*/group* 🎟 Gruppenchat Funktionen: `/group`
*/shop* 🛍 Durchsuche Shops: `/shop` oder `/shop <user/shop_id>`
*/generate* 🎆 Generiere Bilder mit DALLE-2: `/generate <beschreibung>`
*/chat* 💬 Chatte mit GPT: `/chat <nachricht>`"""
# 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
@@ -182,6 +186,7 @@ sendHelpText = """📖 Ups, das hat nicht geklappt. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Du hast %d sat erhalten."""
invoiceReceivedCurrencyMessage = """⚡️ Du hast %d sat (%.2f %s) erhalten."""
invoiceEnterAmountMessage = """Hast du einen Betrag eingegeben?"""
invoiceValidAmountMessage = """Hast du einen gültigen Betrag eingegeben?"""
invoiceHelpText = """📖 Ups, das hat nicht geklappt. %s
@@ -259,11 +264,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
+35 -9
View File
@@ -123,16 +123,19 @@ advancedMessage = """%s
⚙️ *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>`
*/lnurl* ⚡️ Lnurl receive or pay: `/lnurl` or `/lnurl <lnurl> [memo]`
*/nostr* 💜 Connect to Nostr: `/nostr`
*/faucet* 🚰 Create a faucet: `/faucet <capacity> <per_user>`
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
*/group* 🎟 Group chat features: `/group`
*/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
@@ -186,6 +189,7 @@ sendHelpText = """📖 Oops, that didn't work. %s
# INVOICE
invoiceReceivedMessage = """⚡️ You received %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ You received %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Did you enter an amount?"""
invoiceValidAmountMessage = """Did you enter a valid amount?"""
invoiceHelpText = """📖 Oops, that didn't work. %s
@@ -264,13 +268,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*, 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."""
@@ -358,14 +372,21 @@ groupJoinGroupHelpMessage = """📖 Oops, that didn't work. Please try
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."""
groupBotIsNotAdminMessage = """🚫 Oops, that didn't work. You must make me admin and grant me rights to invite and ban 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`."""
groupAddedMessagePrivate = """🎟 Tickets for group `%s` added.\n\nAlias: `%s` Price: %d sat\n\nTo request a ticket for this group, start a private chat with %s and write `/join %s`."""
groupAddedMessagePublic = """🎟 Tickets enabled."""
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 🎟
groupHelpMessage = """👥 *Group commands*
🎟 *Public tickets*
For admins (in group chat): `/group ticket <ticket_price>`\nExample: `/group ticket 1000`
🎟 *Private tickets*
Sell tickets for your _private Group_ and get rid of spam bots.
@@ -382,5 +403,10 @@ _Fees: The bot takes a 10%% +10 sat commission for cheap tickets. If the ticket
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`"""
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 -2
View File
@@ -119,11 +119,13 @@ advancedMessage = """%s
⚙️ *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>`
*/lnurl* ⚡️ Lnurl recibir o pagar: `/lnurl` o `/lnurl <lnurl> [memo]`
*/nostr* 💜 Conectar a Nostr: `/nostr`
*/faucet* 🚰 Crear un grifo: `/faucet <capacidad> <por_usuario>`
*/tipjar* 🍯 Crear un tipjar: `/tipjar <capacidad> <por_usuario>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
*/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."""
@@ -182,6 +184,7 @@ sendHelpText = """📖 Oops, eso no funcionó. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Recibiste %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Recibiste %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """¿Ingresaste un monto?"""
invoiceValidAmountMessage = """¿Ingresaste un monto válido?"""
invoiceHelpText = """📖 Oops, eso no funcionó. %s
+412
View File
@@ -0,0 +1,412 @@
# COMMANDS
helpCommandStr = """ohje"""
basicsCommandStr = """peruskomennot"""
tipCommandStr = """tippi"""
balanceCommandStr = """saldo"""
sendCommandStr = """lähetä"""
invoiceCommandStr = """laskuta"""
payCommandStr = """maksa"""
donateCommandStr = """lahjoita"""
advancedCommandStr = """lisäkomennot"""
transactionsCommandStr = """tapahtumat"""
logCommandStr = """loki"""
listCommandStr = """lista"""
linkCommandStr = """linkki"""
lnurlCommandStr = """lnurl"""
faucetCommandStr = """hana"""
tipjarCommandStr = """tippikulho"""
receiveCommandStr = """vastaanota"""
hideCommandStr = """piilota"""
volcanoCommandStr = """tulivuori"""
showCommandStr = """näytä"""
optionsCommandStr = """valinnat"""
settingsCommandStr = """asetukset"""
saveCommandStr = """tallenna"""
deleteCommandStr = """poista"""
infoCommandStr = """tiedot"""
# NOTIFICATIONS
cantDoThatMessage = """Et voi tehdä tuota."""
cantClickMessage = """Et voi painaa tätä nappia."""
balanceTooLowMessage = """Saldosi on liian pieni."""
# BUTTONS
sendButtonMessage = """✅ Lähetä"""
payButtonMessage = """✅ Maksa"""
payReceiveButtonMessage = """💸 Maksa"""
receiveButtonMessage = """✅ Vastaanota"""
withdrawButtonMessage = """✅ Nosta"""
cancelButtonMessage = """🚫 Peruuta"""
collectButtonMessage = """✅ Kerää"""
nextButtonMessage = """Seuraava"""
backButtonMessage = """Edellinen"""
acceptButtonMessage = """Hyväksy"""
denyButtonMessage = """Hylkää"""
tipButtonMessage = """Tippi"""
revealButtonMessage = """Paljasta"""
showButtonMessage = """Näytä"""
hideButtonMessage = """Piilota"""
joinButtonMessage = """Liity"""
optionsButtonMessage = """Valinnat"""
settingsButtonMessage = """Asetukset"""
saveButtonMessage = """Tallenna"""
deleteButtonMessage = """Poista"""
infoButtonMessage = """Tiedot"""
cancelButtonEmoji = """🚫"""
payButtonEmoji = """💸"""
# HELP
helpMessage = """⚡️ *Lompakko*
_Tämä botti on Bitcoin Lightning -lompakko ja sitä käytetään Telegram:in sisällä tippien lähettämiseen. Botti on lisättävä jäseneksi ryhmäkeskusteluun, jotta se voi toimia. Tippien rahayksikkö on satoshi (sat). 100,000,000 sat = 1 Bitcoin. Kirjoita 📚 /basics lukeaksesi lisää._
❤️ *Lahjoitus*
_Tämä botti ei veloita kuluja, mutta sen ylläpidosta aiheutuu kuluja. Jos tykkäät botista, niin harkitsethan lahjoituksen tekemistä projektille. Lahjoituksen voit tehdä komennolla_ `/donate 1000`
%s
⚙️ *Komennot*
*/tip* 🏅 Lähetä tippi liittämällä vastausviestiin: `/tip <amount> [<memo>]`
*/balance* 👑 Tarkista saldosi: `/balance`
*/send* 💸 Lähetä varoja käyttäjälle: `/send <amount> @user or user@ln.tips [<memo>]`
*/invoice* ⚡️ Vastaanota Lightning-maksu: `/invoice <amount> [<memo>]`
*/pay* ⚡️ Lähetä Lightning-maksu: `/pay <invoice>`
*/donate* ❤️ Lahjoitus LightningTipBot-tiimille: `/donate 1000`
*/advanced* 🤖 Lisäasetukset.
*/help* 📖 Lue tämä ohje."""
infoHelpMessage = """ℹ️ *Tiedot*"""
infoYourLightningAddress = """Lightning Address -osoitteesi on `%s`"""
basicsMessage = """🧡 *Bitcoin*
_Bitcoin on internetin raha. Se on hajautettu ja vapaa, eikä sillä ole johtajia tai hallinnoijia. Bitcoin on kovaa rahaa. Se on myös nopeampi, turvallisempi ja laajemmin toimiva kuin perinteiset pankkijärjestelmät tai valuutat._
🧮 *Ekonomia*
_Bitcoinin pienin yksikkö on satoshi (sat) ja 100.000.000 sat = 1 Bitcoin. Bitcoineja tulee kostkaan olemaan enintään 21 miljoonaa kappaletta. Bitcoinin päivittäinen valuuttavaihtokurssi vaihtelee päivittän, mutta jos elät Bitcoin standardin mukaisesti on kuitenkin 1 sat aina 1 sat._
⚡️ *Lightning-verkko*
_Lightning-verkko on maksuprotokolla, joka mahdollistaa nopeat ja edulliset bitcoin-siirrot, eikä se juurikaan kuluta energiaa. Sen avulla miljardit ihmiset ympäri maailmaa pystyvät käyttämään Bitcoinia._
📲 *Lightning-lompakot*
_Tämän botin lompakosta voit lähettää, tai vastaanottaa siihen, varoja kenen tahansa omistaman Lightning-lompakon välillä. Suositeltuja muita lompakkoja mobiililaitteisiin ovat_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (non-custodial), tai_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(helppo)_.
📄 *Open Source*
_Tämä bottiohjelmisto on vapaa ja_ [open source](https://github.com/LightningTipBot/LightningTipBot) _ohjelmisto. Voit ajaa bottia omassa tietokoneessasi ja käyttää sitä yhdessä lähipiirisi kanssa._
✈️ *Telegram*
_Lisää tämä botti Telegram-ryhmäkeskusteluun, ja /tip -komennolla voit tipata kuita keskustelijoita. Kun määrität botin ryhmän pääkäyttäjäksi (admin), niin se myös siivoaa myös bottikomennot pois keskustelusta ja ryhmäsi sisältö pysyy siistinä._
🏛 *Ehdot*
_Me emme pidä varojasi hallussa. Toimimme sinun parhaaksesi ja tiedämme KYC-henkilötunnistautumisen vaatimukset. Ne ovat aika mutkikkaita, kunnes keksimme asiaan ratkaisun. Käsittelemme kaikkia lompakossasi olevia varoja lahjoituksina. Älä siis lahjoita meille kaikkia varojasi. Huomioi myös että tämä botti on ns beta-kehitysvaiheessa ja huomioit riskit botin mahdollisesti tekemistä virheistä._
❤️ *Lahjoitus*
_Tämä botti ei veloita kuluja, mutta sen ylläpidosta aiheutuu kuluja. Jos tykkäät botista, niin harkitsethan lahjoituksen tekemistä projektille. Lahjoituksen voit tehdä komennolla_ `/donate 1000`"""
helpNoUsernameMessage = """👋 Ole hyvä ja määritä Telegram-käyttäjänimesi."""
advancedMessage = """%s
👉 *Keskustelun komennot*
*send* 💸 Lähetä satteja keskusteluun: `%s send <amount> [<user>] [<memo>]`
*receive* 🏅 Pyydä maksua: `... receive <amount> [<user>] [<memo>]`
*faucet* 🚰 Luo hana: `... faucet <capacity> <per_user> [<memo>]`
*tipjar* 🍯 Luo tippikulho: `... tipjar <capacity> <per_user> [<memo>]`
📖 Keskustelu komennot ovat käytettävissä kaikissa keskusteluissa, jopa kahdenkeskisissä. Kun olet kirjoittanut keskustelussa komennon, niin odota hetkinen vaihtoehtoja - älä paina Enteriä.
⚙️ *Edistyneemmät komennot*
*/transactions* 📊 Maksutapahtumien listaus
*/link* 🔗 Linkitä lompakkosi [BlueWallet](https://bluewallet.io/) tai [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Vastaanota tai maksa Lnurl: `/lnurl` or `/lnurl <lnurl> [memo]`
*/nostr* 💜 Yhdistä nostr: `/nostr`
*/faucet* 🚰 Luo hana: `/faucet <capacity> <per_user>`
*/tipjar* 🍯 Luo tippikulho: `/tipjar <capacity> <per_user>`
*/group* 🎟 Ryhmäkeskustelun toiminnot: `/group`
*/shop* 🛍 Selaa kauppoja: `/shop` or `/shop <user/shop_id>`
*/generate* 🎆 Luo DALLE-2 kuvia: `/generate <prompt>`"""
# GENERIC
enterAmountRangeMessage = """💯 Syötä määrä %d ja %d sat väliltä."""
enterAmountMessage = """💯 Syötä määrä."""
enterUserMessage = """👤 Syötä käyttäjä."""
enterTextMessage = """⌨️ Syötä teksti."""
errorReasonMessage = """🚫 Virhe: %s"""
# START
startSettingWalletMessage = """🧮 Lompakkoasi määritetään..."""
startWalletCreatedMessage = """🧮 Lompakkosi on luotu."""
startWalletReadyMessage = """✅ *Lompakkosi on valmis.*"""
startWalletErrorMessage = """🚫 Lompakon määritys tai avaus epäonnistui. Yritä myöhemmin uudelleen."""
startNoUsernameMessage = """☝️ Näyttäisi että sinulla ei ole vielä Telegram @username -käyttäjätunnusta. Se ei haittaa, voit kuitenkin käyttää tätä bottia. Saat kuitenkin botin käytöstä enemmän irti, kun asetat itsellesi käyttäjänimen Telegram-asetuksista. Sen tehtyäsi syötä komento /balance ja botti päivittää tietosi."""
# BALANCE
balanceMessage = """👑 *Saldosi on:* %d sat"""
balanceErrorMessage = """🚫 Saldosi hakeminen epäonnistui. Yritä myöhemmin uudelleen."""
# TIP
tipDidYouReplyMessage = """Lähetitkö vastauksen siihen viestiin, mitä halusit tipata? Vastaa mihintahansa viestiin tietokoneella klikkaamalla oikealla hiiren napilla viestiä, ja valitse Vastaa tai Reply, mobiililaitteella voit pyyhkäistä viestiä. Jos haluat lähettää suoraan varoja toiselle käyttäjälle, niin se onnistuu /send -komennolla."""
tipInviteGroupMessage = """ℹ️ Muuten, voit kutsua tämän botin mihin tahansa ryhmään ja käyttää bottia siellä tippien lähettämiseen."""
tipEnterAmountMessage = """Syötithän määrän?"""
tipValidAmountMessage = """Syötithän määrän oikein?"""
tipYourselfMessage = """📖 Et voi lähettää tippiä itsellesi."""
tipSentMessage = """💸 %d sat läheteettiin %s:lle."""
tipReceivedMessage = """🏅 %s lähetti sinulle %d sat tipin."""
tipErrorMessage = """🚫 Tippi epäonnistui."""
tipUndefinedErrorMsg = """yritä myöhemmin uudelleen."""
tipHelpText = """📖 Hups, sepä ei toiminutkaan. %s
*Muoto:* `/tip <amount> [<memo>]`
*Esimerkki:* `/tip 1000 Kiitti meemistä!`"""
# SEND
sendValidAmountMessage = """Syötithän määrän oikein?"""
sendUserHasNoWalletMessage = """🚫 Käyttäjällä %s ei ole lompakkoa."""
sendSentMessage = """💸 %d sat lähetettiin %s:lle."""
sendPublicSentMessage = """💸 %d sat lähetettiin %s:ltä to %s:lle."""
sendReceivedMessage = """🏅 %s lähetti sinulle %d sat."""
sendErrorMessage = """🚫 Lähetys epäonnistu."""
confirmSendMessage = """Haluatko lähettää vastaanottajalle %s?\n\n💸 Määrä: %d sat"""
confirmSendAppendMemo = """\n✉️ %s"""
sendCancelledMessage = """🚫 Lähetys peruutettu."""
errorTryLaterMessage = """🚫 Virhe. Yritä myöhemmin uudelleen."""
sendSyntaxErrorMessage = """Annoithan määrän ja vastaanottajan? Lähetä /send komennolla joko Telegram-käyttäjänimelle (kuten %s) tai Lightning Address -osoitteeseen muotoa LightningTipBot@ln.tips."""
sendHelpText = """📖 Hups, sepä ei toiminutkaan. %s
*Muoto:* `/send <amount> <user> [<memo>]`
*Esimerkki:* `/send 1000 @LightningTipBot Rakastan bottia ❤️`
*Esimerkki:* `/send 1234 LightningTipBot@ln.tips`"""
# INVOICE
invoiceReceivedMessage = """⚡️ Vastaanotit %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Vastaanotit %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Syötithän määrän?"""
invoiceValidAmountMessage = """Syötithän määrän oikein?"""
invoiceHelpText = """📖 Hups, sepä ei toiminutkaan. %s
*Muoto:* `/invoice <amount> [<memo>]`
*Esimerkki:* `/invoice 1000 Kiitos!`"""
invoicePaidText = """✅ Lasku maksettu."""
# PAY
paymentCancelledMessage = """🚫 Maksu peruutettu."""
invoicePaidMessage = """⚡️ Maksu lähetettiin."""
invoicePublicPaidMessage = """⚡️ Maksun lähetti %s."""
invalidInvoiceHelpMessage = """Syötithän Lightning-laskun oikein? Käytä /send -komentoa jos haluat lähettää Telegram-käyttäjälle tai Lightning Address -osoitteeseen."""
invoiceNoAmountMessage = """🚫 Laskua ei voi maksaa ilman määrää."""
insufficientFundsMessage = """🚫 Varat eivät riitä. Sinulla on %d sat mutta tarvitset vähintään %d sat."""
feeReserveMessage = """⚠️ Koko saldosi lähettäminen ei todennäköisesti onnistu, koska maksun käsittelystä menee kuluja. Varaa vähintään 1% kuluihin."""
invoicePaymentFailedMessage = """🚫 Maksu epäonnistui: %s"""
invoiceUndefinedErrorMessage = """Laskun maksu epäonnistui."""
confirmPayInvoiceMessage = """Vahvista maksun lähetys?\n\n💸 Määrä: %d sat"""
confirmPayAppendMemo = """\n✉️ %s"""
payHelpText = """📖 Hups, sepä ei toiminutkaan. %s
*Muoto:* `/pay <invoice>`
*Esimerkki:* `/pay lnbc20n1psscehd...`"""
# DONATE
donationSuccess = """🙏 Kiitoksia lahjoituksesta."""
donationErrorMessage = """🚫 Oi ei! Lahjoitus epäonnistui."""
donationProgressMessage = """🧮 Valmistellaan lahjoitusta..."""
donationFailedMessage = """🚫 Lahjoitus epäonnistui: %s"""
donateEnterAmountMessage = """Syötithän määrän?"""
donateValidAmountMessage = """Syötithän määrän oikein?"""
donateHelpText = """📖 Hups, sepä ei toiminutkaan. %s
*Muoto:* `/donate <amount>`
*Esimerkki:* `/donate 1000`"""
# PHOTO
photoQrNotRecognizedMessage = """🚫 Lightning- tai LNURL -laskun tunnistus epäonnistui. Koeta keskittää QR-koodi, leikkaa kuvaa tai zoomaa tarkemmaksi."""
photoQrRecognizedMessage = """✅ QR-koodi:
`%s`"""
# LNURL
lnurlReceiveInfoText = """👇 Voit ottaa maksuja vastaan tämän kiinteän LNURL:in avulla."""
lnurlResolvingUrlMessage = """🧮 Selvitetään osoitetta..."""
lnurlGettingUserMessage = """🧮 Valmistellaan maksua..."""
lnurlPaymentFailed = """🚫 Maksu epäonnistui: %s"""
lnurlInvalidAmountMessage = """🚫 Virheellinen määrä."""
lnurlInvalidAmountRangeMessage = """🚫 Määrän tulee olla %d ja %d sat väliltä."""
lnurlNoUsernameMessage = """🚫 LNURL:in avulla maksujen vastaanotto edellyttää että, sinulla on Telegram-käyttäjätunnus määriteltynä."""
lnurlHelpText = """📖 Hups, sepä ei toiminutkaan. %s
*Muoto:* `/lnurl [amount] <lnurl>`
*Esimerkki:* `/lnurl LNURL1DP68GUR...`"""
# LNURL LOGIN
confirmLnurlAuthMessager = """Haluatko kirjautua %s?"""
lnurlSuccessfulLogin = """✅ Kirjautuminen onnistui."""
loginButtonMessage = """✅ Kirjautuminen"""
loginCancelledMessage = """🚫 Kirjautuminen peruutettiin."""
# LNURL WITHDRAW
confirmLnurlWithdrawMessage = """Haluatko toteuttaa noston?\n\n💸 Määrä: %d sat"""
lnurlPreparingWithdraw = """🧮 Valmistellaan nostoa..."""
lnurlWithdrawFailed = """🚫 Nosto epäonnistui."""
lnurlWithdrawCancelled = """🚫 Nosto peruutettiin."""
lnurlWithdrawSuccess = """✅ Nosto käsitelty."""
# LINK
walletConnectMessage = """🔗 *Linkitä lompakkosi*
⚠️ Älä koskaan paljasta seuraavia URL-osoitetta tai QR-koodia kenellekään. Niiden avulla pääsee käsiksi botissa oleviin varoihisi. jos tarvitse API-avaimia, käytä /api -komentoa.
- *BlueWallet:* Paina *New wallet*, *Import wallet*, *Scan or import a file*, ja lue QR-koodi.
- *Zeus:* Kopioi alla oleva URL, valitse *Add a new node* ja Node interface kohdasta *LNDHub*, syötä URL ja paina *Save Node Config*."""
couldNotLinkMessage = """🚫 Lompakon linkitys epäonnistui. Yritä myöhemmin uudelleen."""
linkHiddenMessage = """🔍 Linkki on piilotettu. Käytä /link -komentoa nähdäksesi sen uudelleen."""
# API
apiConnectMessage = """🔗 *Sinun API avaimet*
⚠️ Älä koskaan paljasta API-avaimia kenellekään. Niiden avulla pääsee käsiksi botissa oleviin varoihisi. Käytä /link -komentoa yhdistääksesi ulkoiseen lompakkoon.
- *Admin key:* `%s`
- *Invoice key:* `%s`"""
apiHiddenMessage = """🔍 Avaimet on piilotettu. Käytä /api -komentoa nähdäksesi ne uudelleen."""
# FAUCET
inlineQueryFaucetTitle = """🚰 Luo hana."""
inlineQueryFaucetDescription = """Muoto: @%s faucet <capacity> <per_user>"""
inlineResultFaucetTitle = """🚰 Luo hana %d sat kapasiteetilla."""
inlineResultFaucetDescription = """👉 Paina tästä luodaksesi hanan tähän keskusteluun."""
inlineFaucetMessage = """Painamalla ✅ nostat %d sat %s:n tekemästä hanasta.
🚰 Jäljellä: %d/%d sat (nostettu %d/%d käyttäjälle)
%s"""
inlineFaucetEndedMessage = """🚰 Hana on tyhjä 🍺\n\n🏅 %d sat annettiin %d käyttäjälle."""
inlineFaucetAppendMemo = """\n✉️ %s"""
inlineFaucetCreateWalletMessage = """Hallinnoi lompakkoasti viestillä %s:lle 👈 ."""
inlineFaucetCancelledMessage = """🚫 Hana suljettu."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Hanan käyttäjäkohtainen kapasiteetti ei jakaudu tasan tai se on liian pieni (min 5 sat)."""
inlineFaucetInvalidAmountMessage = """🚫 Virheellinen määrä."""
inlineFaucetSentMessage = """🚰 %d sat lähetetty %s."""
inlineFaucetReceivedMessage = """🚰 %s lähetti sinulle %d sat."""
inlineFaucetHelpFaucetInGroup = """Luo botin avulla ryhmäkeskusteluun hana tai käytä 👉 keskustelun komentoja (/advanced lisätoimintoja)."""
inlineFaucetAlreadyTookMessage = """🚫 Olet jo nostanut varoja tästä hanasta."""
inlineFaucetHelpText = """📖 Hups, sepä ei toiminutkaan. %s
*Muoto:* `/faucet <capacity> <per_user>`
*Esimerkki:* `/faucet 210 21`"""
# INLINE SEND
inlineQuerySendTitle = """💸 Lähetä maksu keskusteluun."""
inlineQuerySendDescription = """Muoto: @%s send <amount> [<user>] [<memo>]"""
inlineResultSendTitle = """💸 Lähetä %d sat."""
inlineResultSendDescription = """👉 Paina tästä lähettääksesi %d sat tähän keskusteluun."""
inlineSendMessage = """Paina ✅ vastaanottaaksesi maksun %s:ltä.\n\n💸 Määrä: %d sat"""
inlineSendAppendMemo = """\n✉️ %s"""
inlineSendUpdateMessageAccept = """💸 %d sat lähetty %s:ltä %s:lle."""
inlineSendCreateWalletMessage = """Avaa keskustelu %s :lle 👈 ja hallinnoi lompakkoasi."""
sendYourselfMessage = """📖 Et voi maksaa itsellesi."""
inlineSendFailedMessage = """🚫 Lähetys epäonnistui."""
inlineSendInvalidAmountMessage = """🚫 Määrän pitää olla nollaa suurempi."""
inlineSendBalanceLowMessage = """🚫 Saldosi on liian pieni."""
# INLINE RECEIVE
inlineQueryReceiveTitle = """🏅 Pyydä maksua keskustelussa."""
inlineQueryReceiveDescription = """Muoto: @%s receive <amount> [<user>] [<memo>]"""
inlineResultReceiveTitle = """🏅 Vastaanota %d sat."""
inlineResultReceiveDescription = """👉 Paina tästä vastaanottaaksesi %d sat."""
inlineReceiveMessage = """Paina 💸 maksaaksesi %s:lle.\n\n💸 Määrä: %d sat"""
inlineReceiveAppendMemo = """\n✉️ %s"""
inlineReceiveUpdateMessageAccept = """💸 %d sat lähetetty %s:ltä %s:lle."""
inlineReceiveCreateWalletMessage = """Avaa keskustelu %s :lle 👈 ja hallinnoi lompakkoasi."""
inlineReceiveYourselfMessage = """📖 Et voi maksaa itsellesi."""
inlineReceiveFailedMessage = """🚫 Vastaanotto epäonnistui."""
inlineReceiveCancelledMessage = """🚫 Vastaanotto peruutettu."""
# TIPJAR
inlineQueryTipjarTitle = """🍯 Luo tippikulho."""
inlineQueryTipjarDescription = """Muoto: @%s tipjar <capacity> <per_user>"""
inlineResultTipjarTitle = """🍯 Luo %d sat tippikulho."""
inlineResultTipjarDescription = """👉 Paina tästä luodaksesi tippikulhon tähän keskusteluun."""
inlineTipjarMessage = """Paina 💸 *maksaaksesi %d sat* %s:n luomaan tippikulhoon.
🙏 Tippikulhossa: *%d*/%d sat (%d käyttäjältä)
%s"""
inlineTipjarEndedMessage = """🍯 %s:n tippikulho on täynnä⭐️\n\n🏅 %d sat saatin %d käyttäjältä."""
inlineTipjarAppendMemo = """\n✉️ %s"""
inlineTipjarCancelledMessage = """🚫 Tippikulho poistettu."""
inlineTipjarInvalidPeruserAmountMessage = """🚫 Käyttäjäkohtainen määrä ei ole jaollinen kapasiteetilla."""
inlineTipjarInvalidAmountMessage = """🚫 Virheellinen määrä."""
inlineTipjarSentMessage = """🍯 %d sat lähetty %s:lle."""
inlineTipjarReceivedMessage = """🍯 %s lähetti sinulle %d sat."""
inlineTipjarHelpTipjarInGroup = """Luo tippikulho ryhmään, jossa botti on jäsenenä tai käytä 👉 keskustelun komentoa (/advanced lisätoimintoja)."""
inlineTipjarHelpText = """📖 Hups, sepä ei toiminutkaan. %s
*Muoto:* `/tipjar <capacity> <per_user>`
*Esimerkki:* `/tipjar 210 21`"""
# GROUP TICKETS
groupAddGroupHelpMessage = """📖 Hups, sepä ei toiminutkaan. Tämä toiminto on käytettävissä vain ryhmäkeskusteluissa ja sitä voi käyttää ainoastaan ryhmän omistaja.\nMuoto: `/group add <group_name> [<amount>]`\nExample: `/group add TheBestBitcoinGroup 1000`"""
groupJoinGroupHelpMessage = """📖 Hups, sepä ei toiminutkaan. Yritä uudelleen.\nMuoto: `/join <group_name>`\nExample: `/join TheBestBitcoinGroup`"""
groupClickToJoinMessage = """🎟 [Paina tästä](%s) 👈 liittyäksesi `%s`."""
groupTicketIssuedGroupMessage = """🎟 Käyttäjä %s on saanut pääsyn tähän ryhmään."""
groupPayInvoiceMessage = """🎟 Maksa yllä oleva lasku, jotta voit liittyä ryhmään %s."""
groupBotIsNotAdminMessage = """🚫 Hups, sepä ei toiminutkaan. Sinun pitää lisätä minut ryhmän pääkäyttäjäksi ja antaa minulle oikeudet lisätä ja bannata käyttäjiä."""
groupNameExists = """🚫 Tämän niminen ryhmä on jo olemassa. Valitse ryhmälle uusi nimi."""
groupAddedMessagePrivate = """🎟 Ryhmään `%s` on lisätty pääsymaksut.\n\nAlias: `%s` Hinta: %d sat\n\nKun haluat pääsyn tähän ryhmään, aloita keskustelu %s:n kanssa ja anna komento `/join %s`."""
groupAddedMessagePublic = """🎟 Pääsymaksut otettu käyttöön."""
groupNotFoundMessage = """🚫 Tämän nimistä ryhmää ei löydy."""
groupReceiveTicketInvoiceCommission = """🎟 Vastaanotit *%d sat* (mistä on vähennetty %d sat komissio) käyttäjän %s pääsymaksuna ryhmään `%s` ."""
groupReceiveTicketInvoice = """🎟 Vastaanotit *%d sat* käyttäjän %s pääsymaksuna ryhmään `%s`."""
commandPrivateMessage = """Käytä tätä komentoa %s:n kanssa kahdenkeskisessä keskustelussa."""
groupHelpMessage = """👥 *Ryhmäkomennot*
🎟 *Julkiset pääsymaksut*
Pääkäyttäjille (ryhmäkeskustelussa): `/group ticket <ticket_price>`\nExample: `/group ticket 1000`
🎟 *Yksityiset pääsymaksut*
Veloita pääsymaksuja sinun _yksityiseen ryhmään_ ja pidät spammibotit poissa.
*Ohjeet ryhmän pääkäyttäjille:*
1) Kutsu ryhmääsi jäseneksi %s ja anna sille pääkäyttäjä (admin) oikeudet.
2) Muuta ryhmäsi yksityiseksi (private).
3) Ryhmässä, sinun (ryhmän omistaja) pitää antaa komento `/group add <mygroup> [<ticket_price>]`.
_Kulut: botti veloittaa 10%% +10 sat komission edullisista pääsymaksuista. Jos pääsymaksu on >= 1000 sat, niin komissio on 2%% + 100 sat._
*Ohjeet ryhmän jäsenille:*
Liittyäksesi ryhmään, aloita keskustelu %s:n kanssa ja kirjoita kahdenkeskiseen keskusteluun viesti `/join <mygroup>`.
📖 *Muoto:*
Pääkäyttäjille (ryhmissä): `/group add <group_name> [<ticket_price>]`\nEsimerkki: `/group add TheBestBitcoinGroup 1000`
Käyttäjille (yksityskeskusteluissa): `/join <group_name>`\nEsimerkki: `/join TheBestBitcoinGroup`"""
# DALLE GENERATE
generateDalleHelpMessage = """Luo OpenAI DALLE 2. -kuvia\nUsage: `/generate <prompt>`\nPrice: 1000 sat"""
generateDallePayInvoiceMessage = """Maksa tämä lasku ja neljä kuvaa luotaan 👇"""
generateDalleGeneratingMessage = """Kuvia luodaan. Odota hetkinen..."""
+6 -3
View File
@@ -119,11 +119,13 @@ advancedMessage = """%s
⚙️ *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>`
*/lnurl* ⚡️ Lnurl recevoir ou payer: `/lnurl` ou `/lnurl <lnurl> [memo]`
*/nostr* 💜 Connect to Nostr: `/nostr`
*/faucet* 🚰 Créer un faucet: `/faucet <capacité> <par_utilisateur>`
*/tipjar* 🍯 Créer un tipjar: `/tipjar <capacité> <par_utilisateur>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
*/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."""
@@ -182,6 +184,7 @@ sendHelpText = """📖 Oops, cela n'a pas fonctionné. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Vous avez reçu %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Vous avez reçu %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Avez-vous choisi un montant ?"""
invoiceValidAmountMessage = """Avez-vous choisi un montant correct ?"""
invoiceHelpText = """📖 Oops, cela n'a pas fonctionné. %s
@@ -228,7 +231,7 @@ photoQrRecognizedMessage = """✅ QR code:
# LNURL
lnurlReceiveInfoText = """👇 Vous ne pouvez pas utiliser cet LNURL pour recevoir des paiements."""
lnurlReceiveInfoText = """👇 Vous pouvez utiliser cet LNURL pour recevoir des paiements."""
lnurlResolvingUrlMessage = """🧮 Recherche de l'adresse..."""
lnurlGettingUserMessage = """🧮 Préparation du paiement..."""
lnurlPaymentFailed = """🚫 Echec du paiement : %s"""
+5 -2
View File
@@ -119,11 +119,13 @@ advancedMessage = """%s
⚙️ *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>`
*/lnurl* ⚡️ Lnurl menerima atau membayar: `/lnurl` atau `/lnurl <lnurl> [memo]`
*/nostr* 💜 Connect to Nostr: `/nostr`
*/faucet* 🚰 Membuat sebuah keran `/faucet <kapasitas> <per_pengguna>`
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
*/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."""
@@ -182,6 +184,7 @@ sendHelpText = """📖 Waduh, itu tidak berhasil. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Kamu menerima %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Kamu menerima %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Apakah kamu sudah memasukkan jumlah?"""
invoiceValidAmountMessage = """Apakah kamu memasukkan jumlah yang benar?"""
invoiceHelpText = """📖 Waduh, itu tidak berhasil. %s
+5 -2
View File
@@ -119,11 +119,13 @@ advancedMessage = """%s
⚙️ *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>`
*/lnurl* ⚡️ Ricevi o paga un Lnurl: `/lnurl` or `/lnurl <lnurl> [memo]`
*/nostr* 💜 Connect to Nostr: `/nostr`
*/faucet* 🚰 Crea una distribuzione: `/faucet <totale> <per_utente>`
*/tipjar* 🍯 Crea un tipjar: `/tipjar <totale> <per_utente>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
*/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."""
@@ -182,6 +184,7 @@ sendHelpText = """📖 Ops, non ha funzionato. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Hai ricevuto %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Hai ricevuto %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Hai inserito un ammontare?"""
invoiceValidAmountMessage = """Hai inserito un ammontare valido?"""
invoiceHelpText = """📖 Ops, non ha funzionato. %s
+5 -2
View File
@@ -119,11 +119,13 @@ advancedMessage = """%s
⚙️ *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>`
*/lnurl* ⚡️ Lnurl ontvangen of betalen: `/lnurl` of `/lnurl <lnurl> [memo]`
*/nostr* 💜 Connect to Nostr: `/nostr`
*/faucet* 🚰 Maak een kraan: `/faucet <capacity> <per_user>`
*/tipjar* 🍯 Maak een tipjar: `/tipjar <capacity> <per_user>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
*/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."""
@@ -182,6 +184,7 @@ sendHelpText = """📖 Oeps, dat werkte niet. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Je hebt %d sat ontvangen ."""
invoiceReceivedCurrencyMessage = """⚡️ Je hebt %d sat (%.2f %s) ontvangen."""
invoiceEnterAmountMessage = """Heb je een bedrag ingevoerd?"""
invoiceValidAmountMessage = """Heeft u een geldig bedrag ingevoerd?"""
invoiceHelpText = """📖 Oeps, dat werkte niet. %s
+406
View File
@@ -0,0 +1,406 @@
# COMMANDS
helpCommandStr = """pomoc"""
basicsCommandStr = """podstawy"""
tipCommandStr = """tip"""
balanceCommandStr = """saldo"""
sendCommandStr = """wyślij"""
invoiceCommandStr = """faktura"""
payCommandStr = """pay"""
donateCommandStr = """donate"""
advancedCommandStr = """advanced"""
transactionsCommandStr = """transactions"""
logCommandStr = """log"""
listCommandStr = """list"""
linkCommandStr = """link"""
lnurlCommandStr = """lnurl"""
faucetCommandStr = """faucet"""
tipjarCommandStr = """tipjar"""
receiveCommandStr = """receive"""
hideCommandStr = """hide"""
volcanoCommandStr = """volcano"""
showCommandStr = """show"""
optionsCommandStr = """options"""
settingsCommandStr = """settings"""
saveCommandStr = """save"""
deleteCommandStr = """delete"""
infoCommandStr = """info"""
# NOTIFICATIONS
cantDoThatMessage = """Nie możesz tego zrobić."""
cantClickMessage = """Nie możesz kliknąć tego przycisku."""
balanceTooLowMessage = """Twoje saldo jest za niskie."""
# BUTTONS
sendButtonMessage = """✅ Wyślij"""
payButtonMessage = """✅ Zapłać"""
payReceiveButtonMessage = """💸 Zapłać"""
receiveButtonMessage = """✅ Otrzymaj"""
withdrawButtonMessage = """✅ Wypłać"""
cancelButtonMessage = """🚫 Anuluj"""
collectButtonMessage = """✅ Odbierz"""
nextButtonMessage = """Dalej"""
backButtonMessage = """Cofnij"""
acceptButtonMessage = """Potwierdź"""
denyButtonMessage = """Odmów"""
tipButtonMessage = """Tip"""
revealButtonMessage = """Ujawnij"""
showButtonMessage = """Pokaż"""
hideButtonMessage = """Ukryj"""
joinButtonMessage = """Dołącz"""
optionsButtonMessage = """Opcje"""
settingsButtonMessage = """Ustawienia"""
saveButtonMessage = """Zapisz"""
deleteButtonMessage = """Skasuj"""
infoButtonMessage = """Informacje"""
cancelButtonEmoji = """🚫"""
payButtonEmoji = """💸"""
# HELP
helpMessage = """⚡️ *Portfel*
_Ten bot jest portfelem Bitcoin Lightning, który potrafi wysyłać napiwki na Telegramie. Aby zacząć dodaj tego bota do chatu grupowego. Podstawową jednostką dla napiwków są Satoshi (sat). 100 000 000 sat = 1 Bitcoin. Napisz 📚 /basics aby uzyskać więcej informacji._
❤️ *Wsparcie*
_Ten bot nie pobiera opłat, ale jego funkcjonowanie kosztuje. Jeśli podoba Ci się, rozważ proszę wsparcie tego projektu darowizną. Aby to zrobić użyj_ `/donate 1000`
%s
⚙️ *Komendy*
*/tip* 🏅 Odpowiedz na wiadomość aby dać napiwek: `/tip <kwota> [<notatka>]`
*/balance* 👑 Sprawdź swoje saldo: `/balance`
*/send* 💸 Wyślij środki do użytkownika: `/send <kwota> @użytkownik lub użytkownik@ln.tips [<notatka>]`
*/invoice* ⚡️ Otrzymaj przy pomocy Lightning: `/invoice <kwota> [<notatka>]`
*/pay* ⚡️ Zapłać przy pomocy Lightning: `/pay <faktura>`
*/donate* ❤️ Wesprzyj projekt darowizną: `/donate 1000`
*/advanced* 🤖 Funkcje zaawansowane.
*/help* 📖 Przeczytaj tę stronę o pomocy."""
infoHelpMessage = """ℹ️ *Informacje*"""
infoYourLightningAddress = """Twój adres Lightning to `%s`"""
basicsMessage = """🧡 *Bitcoin*
_Bitcoin jest walutą internetu. Nie wymaga pozwolenia, jest zdecentralizowany i nie ma władców ani kontrolujących go instytucji. Bitcoin jest twardym pieniądzem, który jest szybszy, bezpieczniejszy i inkluzywny niż dotychczasowy system finansowy._
🧮 *Ekonomia*
_Najmniejszą jednostką Bitcoina są Satoshi (sat) a 100 00 00 sat = 1 Bitcoin. Zawsze będzie tylko 21 milionów Bitcoinów. Ich cena w walucie fiducjarnego może zmieniać się codziennie. Jednak jeśli żyjesz na standardziej Bitcoina 1 sat zawsze będzie równy 1 sat._
⚡️ *Sieć Lightning*
_Sieć Lightning jest protokołem, który umożliwia szybkie i tanie płatności w Bitcoinie, nie potrzebujące do tego prawie żadnej energii. Dzięki temu umożliwia dotarcie do miliardów ludzi na całym świecie._
📲 *Portfele Lightning*
_Twoje środki na tym bocie mogą być wysłane na inne portfele Lightning i vice versa. Rekomendowane portfele dla Twojego telefonu to_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (niepowierniczy), lub_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(łatwy)_.
📄 *Open Source*
_Ten bot to wolne oprogramowanie [open source](https://github.com/LightningTipBot/LightningTipBot)_. Możesz go uruchomić na własnym komputerze i używać we własnej społeczności._
✈️ *Telegram*
_Dodaj tego bota do swojego chatu grupowego na Telegramie aby dawać napiwki za wiadomości. Jeśli uczynisz bota adminem grupy będzie czyścił komendy aby chat był uporządkowany._
🏛 *Warunki*
_Nie jesteśmy powiernikiem Twoich środków. Będziemy działać w Twoim najlepszym interesie ale jesteśmy świadomi tego, że sytuacja bez KYC jest trudna dopóki czegoś nie wymyślimy.
Jakakolwiek kwota, którą załadujesz na portfel będzie traktowana jako darowizna. Nie dawaj nam wszystkich swoich pieniędzy. Wiedz, że ten bota jest w fazie rozwoju beta. Używaj go na własne ryzko._
❤️ *Wesprzyj darowizną*
_Ten bot nie pobiera opłat, ale jego funkcjonowanie kosztuje. Jeśli podoba Ci się, rozważ proszę wsparcie tego projektu darowizną. Aby to zrobić użyj `/donate 1000`"""
helpNoUsernameMessage = """👋 Podaj proszę nazwę swojego użytkownika w Telegramie."""
advancedMessage = """%s
👉 *Komendy inline*
*send* 💸 Wysyła sats na chat: `%s send <kwota> [<użytkownik>] [<notatka>]`
*receive* 🏅 Prosi o płatność: `... receive <kwota> [<użytkownik>] [<notatka>]`
*faucet* 🚰 Tworzy kranik (_faucet_): `... faucet <pojemność> <na_użytkownika> [<notatka>]`
*tipjar* 🍯 Tworzy słoik na napiwki (_tipjar_): `... tipjar <pojemność> <na_użytkownika> [<notatka>]`
📖 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.
⚙️ *Komendy zaawansowane*
*/transactions* 📊 Lista transakcji
*/link* 🔗 Połączenie Twojego portfela z [BlueWallet](https://bluewallet.io/) lub [Zeus](https://zeusln.app/)
*/lnurl* ⚡️ Przyjmij płatność lub zapłać za pomocą Lnurl: `/lnurl` lub `/lnurl <lnurl> [memo]`
*/nostr* 💜 Connect to Nostr: `/nostr`
*/faucet* 🚰 Stwórz kranik (_faucet_): `/faucet <pojemność> <na_użytkownika>`
*/tipjar* 🍯 Stwórz słoik na napiwki (_tipjar_): `/tipjar <pojemność> <na_użytkownika>`
*/group* 🎟 Stwórz bilety na wejście do grupy: `/group add <mojagrupa> [<cena_biletu>]`
*/shop* 🛍 Przeglądaj sklepy: `/shop` lub `/shop <użytkownik/id_sklepu>`
*/generate* 🎆 Generuj obrazy przy użyciu DALLE-2: `/generate <podpowiedź>`"""
# GENERIC
enterAmountRangeMessage = """💯 Wprowadź kwotę między %d a %d sat."""
enterAmountMessage = """💯 Wprowadź kwotę."""
enterUserMessage = """👤 Podaj użytkownika."""
enterTextMessage = """⌨️ Wprowadź tekst."""
errorReasonMessage = """🚫 Błąd: %s"""
# START
startSettingWalletMessage = """🧮 Tworzę Twój portfel..."""
startWalletCreatedMessage = """🧮 Portfel utworzony."""
startWalletReadyMessage = """✅ *Twój portfel jest gotowy.*"""
startWalletErrorMessage = """🚫 Błąd przy inicjowaniu Twojego portfela. Spróbuj ponownie później."""
startNoUsernameMessage = """☝️ Wygląda na to, że nie masz jeszcze nazwy @użytkownika w Telegramie. Nic nie szkodzi, nie potrzebujesz jej by używać tego bota. Jednak aby lepiej go wykorzystać, ustaw nazwę w ustawieniach aplikacji Telegram. Następnie napisz /balance aby bot mógł zaktualizować swoje dane o Tobie."""
# BALANCE
balanceMessage = """👑 *Twoje saldo:* %d sat"""
balanceErrorMessage = """🚫 Pobranie Twojego salda nie powiodło się. Spróbuj ponownie później."""
# TIP
tipDidYouReplyMessage = """Czy odpowiadasz na wiadomość aby dać napiwek? Aby odpowiedzieć na jakąkolwiek wiadomość na komputerze, naciśnij prawy przycisk myszy i wybierz Odpowiedz, a na telefonie przesuń palcem. Jeśli chcesz wysłać bezpośrednio do innego użytkownika użyj komendy /send."""
tipInviteGroupMessage = """ℹ️ Przy okazji, możesz zaprosić tego bota do dowolnej grupy aby zacząć dawać napiwki tam."""
tipEnterAmountMessage = """Czy wprowadzono kwotę?"""
tipValidAmountMessage = """Czy wprowadzono poprawną kwotę?"""
tipYourselfMessage = """📖 Nie możesz dać sobie napiwku."""
tipSentMessage = """💸 %d sat wysłano do %s."""
tipReceivedMessage = """🏅 %s daje Ci napiwek w wysokości %d sat."""
tipErrorMessage = """🚫 Napiwek się nie powiódł."""
tipUndefinedErrorMsg = """spróbuj proszę później."""
tipHelpText = """📖 Ojej, to nie zadziałało. %s
*Użycie:* `/tip <kwota> [<notatka>]`
*Przykład:* `/tip 1000 pojechany mem!`"""
# SEND
sendValidAmountMessage = """Czy podano poprawną kwotę?"""
sendUserHasNoWalletMessage = """🚫 Użytkownik %s jeszcze nie utworzył portfela."""
sendSentMessage = """💸 %d sat wysłano do %s."""
sendPublicSentMessage = """💸 %d sat wysłano od %s do %s."""
sendReceivedMessage = """🏅 %s przysyła Ci %d sat."""
sendErrorMessage = """🚫 Wysłanie nie powiodło się."""
confirmSendMessage = """Czy chcesz zapłacić %s?\n\n💸 Kwota: %d sat"""
confirmSendAppendMemo = """\n✉️ %s"""
sendCancelledMessage = """🚫 Wysłanie anulowane."""
errorTryLaterMessage = """🚫 Błąd. Spróbuj ponownie później."""
sendSyntaxErrorMessage = """Czy wpropwadzono kwotę i odbiorcę? Możesz użyć komendy /send albo żeby wysłać do użytkownika takiego jak %s lub pod adres Lightning taki jak LightningTipBot@ln.tips."""
sendHelpText = """📖 Ojej, to nie zadziałało. %s
*Użycie:* `/send <kwota> <użytkownik> [<notatka>]`
*Przykład:* `/send 1000 @LightningTipBot Po prostu lubię tego bota ❤️`
*Przykład:* `/send 1234 LightningTipBot@ln.tips`"""
# INVOICE
invoiceReceivedMessage = """⚡️ Otrzymujesz %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Otrzymujesz %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Czy wprowadzono kwotę?"""
invoiceValidAmountMessage = """Czy wprowadzono poprawną kwotę?"""
invoiceHelpText = """📖 Ojej, to nie zadziałało. %s
*Użycie:* `/invoice <kwota> [<notatka>]`
*Przykład:* `/invoice 1000 Dziękuję!`"""
invoicePaidText = """✅ Faktura załacona."""
# PAY
paymentCancelledMessage = """🚫 Płatność anulowana."""
invoicePaidMessage = """⚡️ Płatność wysłana."""
invoicePublicPaidMessage = """⚡️ Płatność wysłana przez %s."""
invalidInvoiceHelpMessage = """Czy podajesz poprawną fakturę Lightning? Spróbuj /send jeśli chcesz wysłać do użytkownika na Telegramie lub pod adres Lightning."""
invoiceNoAmountMessage = """🚫 Nie można opłacić faktury bez kwoty."""
insufficientFundsMessage = """🚫 Niewystarczające środki. Masz %d sat a potrzebujesz conajmniej %d sat."""
feeReserveMessage = """⚠️ Wysyłanie swojego całkowitego salda może się nie powieść z powodu opłat sieciowych. Zarezerwuj conajmniej 1% na opłaty."""
invoicePaymentFailedMessage = """🚫 Płatność nie powiodła się: %s"""
invoiceUndefinedErrorMessage = """Nie można było zapłacić faktury."""
confirmPayInvoiceMessage = """Czy chcesz wysłać tę płatność?\n\n💸 Kwota: %d sat"""
confirmPayAppendMemo = """\n✉️ %s"""
payHelpText = """📖 Ojej, to nie zadziałało. %s
*Użycie:* `/pay <faktura>`
*Przykład:* `/pay lnbc20n1psscehd...`"""
# DONATE
donationSuccess = """🙏 Dziękuję za twoją darowiznę."""
donationErrorMessage = """🚫 O nie! Darowizna nie powiodła się."""
donationProgressMessage = """🧮 Przygotowuję Twoją darowiznę..."""
donationFailedMessage = """🚫 Darowizna nie powiodła się: %s"""
donateEnterAmountMessage = """Czy podano kwotę?"""
donateValidAmountMessage = """Czy podano poprawną kwotę?"""
donateHelpText = """📖 Ojej, to nie zadziałało. %s
*Użycie:* `/donate <kwota>`
*Przykład:* `/donate 1000`"""
# PHOTO
photoQrNotRecognizedMessage = """🚫 Nie udało się rozpoznać faktury Lightning ani LNURL. Wypośrodkuj kod QR, przytnij zdjęcie lub powiększ."""
photoQrRecognizedMessage = """✅ Kod QR:
`%s`"""
# LNURL
lnurlReceiveInfoText = """👇 Możesz użyć teego statycznego kodu LNRUL aby otrzymywać płatności."""
lnurlResolvingUrlMessage = """🧮 Rozwiązuje adres..."""
lnurlGettingUserMessage = """🧮 Przygotowuję płatność..."""
lnurlPaymentFailed = """🚫 Płatność się nie powiodła: %s"""
lnurlInvalidAmountMessage = """🚫 Nieprawidłowa kwota."""
lnurlInvalidAmountRangeMessage = """🚫 Kwota musi być między %d a %d sat."""
lnurlNoUsernameMessage = """🚫 Musisz ustawić nazwę użytkownika na Telegramie aby otrzymywać płatności poprzez LNURL."""
lnurlHelpText = """📖 Ojej, to nie zadziałało. %s
*Użycie:* `/lnurl [kwota] <lnurl>`
*Przykład:* `/lnurl LNURL1DP68GUR...`"""
# LNURL LOGIN
confirmLnurlAuthMessager = """Czy chcesz się zalogować do %s?"""
lnurlSuccessfulLogin = """✅ Logowanie udało się."""
loginButtonMessage = """✅ Zaloguj się"""
loginCancelledMessage = """🚫 Logowanie anulowane."""
# LNURL WITHDRAW
confirmLnurlWithdrawMessage = """Czy chcesz dokonąć tej wypłaty?\n\n💸 Kwota: %d sat"""
lnurlPreparingWithdraw = """🧮 Przygotowywanie wypłaty..."""
lnurlWithdrawFailed = """🚫 Wypłata nie powiodła się."""
lnurlWithdrawCancelled = """🚫 Wypłata anulowana."""
lnurlWithdrawSuccess = """✅ Zażądano wypłaty."""
# LINK
walletConnectMessage = """🔗 *Połącz swój portfel*
⚠️ Nigdy nie ujawniaj adresu URL lub kodu QR nikomu, gdyż będą w stanie uzyskać dostęp do Twoich środków. Użyj /api aby uzyskać dostęp do swoich kluczy API.
- *BlueWallet:* Naciśnij *Dodaj porfel*, *Import portfela*, *Skanuj lub importuj plik*, i przeskanuj kod QR.
- *Zeus:* Skopiuj poniższy adres URL, naciśnij *Dodaj nowy węzeł*, wybierz *LNDHub* jako interfejs węzła, wprowadź adres URL, *Zapisz konfigurację węzła*."""
couldNotLinkMessage = """🚫 Nie udało się połączyć Twojego portfela. Spróbuj ponownie później."""
linkHiddenMessage = """🔍 Połączenie ukryto. Napisz /link aby zobaczyć je ponownie."""
# API
apiConnectMessage = """🔗 *Twoje klucze API*
⚠️ Nigdy nie ujawniaj tych kluczy nikomu, gdyż będą w stanie uzyskać dostęp do Twoich środków. Użyj /link aby połączyć swój portfel.
- *Klucz Admin:* `%s`
- *Klucz Invoice:* `%s`"""
apiHiddenMessage = """🔍 Klucze ukryte. Napisz /api aby zobaczyć je ponownie."""
# FAUCET
inlineQueryFaucetTitle = """🚰 Utwórz kranik (_faucet_)."""
inlineQueryFaucetDescription = """Użycie: @%s faucet <pojemność> <na_użytkownika>"""
inlineResultFaucetTitle = """🚰 Tworzenie kranika o pojemności %d sat."""
inlineResultFaucetDescription = """👉 Kliknij tu aby utworzyć kranik w tym chacie."""
inlineFaucetMessage = """Naciśnij ✅ aby zebrać %d sat z kranika %s.
🚰 Pozostało: %d/%d sat (rozdanych %d użytkownikom z %d)
%s"""
inlineFaucetEndedMessage = """🚰 Kranik pusty 🍺\n\n🏅 %d sat rozdano do %d użytkowników."""
inlineFaucetAppendMemo = """\n✉️ %s"""
inlineFaucetCreateWalletMessage = """Chatuj z %s 👈 aby zarządzać swoim portfelem."""
inlineFaucetCancelledMessage = """🚫 Kranik anulowany."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Wartość na_użytkownika nie jest dzielnikiem pojemności lub jest za mała (min 5 sat)."""
inlineFaucetInvalidAmountMessage = """🚫 Nieprawidłowa kwota."""
inlineFaucetSentMessage = """🚰 %d sat wysłano do %s."""
inlineFaucetReceivedMessage = """🚰 %s wysyła Ci %d sat."""
inlineFaucetHelpFaucetInGroup = """Utwórz w grupie z botem kranik (_facuet_) lub użyj 👉 komendy inline (zobacz /advanced aby uzyskać więcej informacji)."""
inlineFaucetAlreadyTookMessage = """🚫 Już brałeś z tego kranika."""
inlineFaucetHelpText = """📖 Ojej, to nie zadziałało. %s
*Użycie:* `/faucet <pojemność> <na_użytkownika>`
*Przykład:* `/faucet 210 21`"""
# INLINE SEND
inlineQuerySendTitle = """💸 Wyślij płatność do tego chatu."""
inlineQuerySendDescription = """Użycie: @%s send <kwota> [<użytkownik>] [<notatka>]"""
inlineResultSendTitle = """💸 Wysłano %d sat."""
inlineResultSendDescription = """👉 Kliknij aby wysłać %d sat do tego chatu."""
inlineSendMessage = """Naciśnij ✅ aby otrzymać płatność od %s.\n\n💸 Kwota: %d sat"""
inlineSendAppendMemo = """\n✉️ %s"""
inlineSendUpdateMessageAccept = """💸 %d sat wysłano od %s do %s."""
inlineSendCreateWalletMessage = """Chatuj z %s 👈 aby zarządzać swoim portfelem."""
sendYourselfMessage = """📖 Nie możesz zapłacić sobie."""
inlineSendFailedMessage = """🚫 Wysłanie nie powiodło się."""
inlineSendInvalidAmountMessage = """🚫 Kwota musi być większa niż 0."""
inlineSendBalanceLowMessage = """🚫 Twoje saldo jest za niskie."""
# INLINE RECEIVE
inlineQueryReceiveTitle = """🏅 Poproś o płatność na chacie."""
inlineQueryReceiveDescription = """Użycie: @%s receive <kwota> [<użytkownik>] [<notatka>]"""
inlineResultReceiveTitle = """🏅 Otrzymaj %d sat."""
inlineResultReceiveDescription = """👉 Kliknij aby poprosić o płatność %d sat."""
inlineReceiveMessage = """Naciśnij 💸 aby zapłacić %s.\n\n💸 Kwota: %d sat"""
inlineReceiveAppendMemo = """\n✉️ %s"""
inlineReceiveUpdateMessageAccept = """💸 %d sat wysłano od %s do %s."""
inlineReceiveCreateWalletMessage = """Chatuj z %s 👈 aby zarządzać swoim portfelem."""
inlineReceiveYourselfMessage = """📖 Nie możesz zapłacić sobie."""
inlineReceiveFailedMessage = """🚫 Przyjmowanie środków nie powiodło się."""
inlineReceiveCancelledMessage = """🚫 Przyjmowanie środków anulowane."""
# TIPJAR
inlineQueryTipjarTitle = """🍯 Utwórz słoik na napiwki (_tipjar_)."""
inlineQueryTipjarDescription = """Użycie: @%s tipjar <pojemność> <na_użytkownika>"""
inlineResultTipjarTitle = """🍯 Tworzenie słoika na napiwki (_tipjar_) o pojemności %d sat."""
inlineResultTipjarDescription = """👉 Kliknij tu aby utworzyć w tym chacie słoik na napiwki (_tipjar_)."""
inlineTipjarMessage = """Naciśnij 💸 aby *wpłacić %d sat* do tego słoika na napiwki (_tipjar_) przez %s.
🙏 Przekazano: *%d*/%d sat (przez %d użytkowników)
%s"""
inlineTipjarEndedMessage = """🍯 Słoik na napiwki %s jest pełen ⭐️\n\n🏅 %d sat przekazanych przez %d użytkowników."""
inlineTipjarAppendMemo = """\n✉️ %s"""
inlineTipjarCancelledMessage = """🚫 Słoik na napiwki anulowany."""
inlineTipjarInvalidPeruserAmountMessage = """🚫 Kwota na_użytkownika nie jest dzielnikiem pojemności."""
inlineTipjarInvalidAmountMessage = """🚫 Nieprawidłowa kwota."""
inlineTipjarSentMessage = """🍯 %d sat wysłano do %s."""
inlineTipjarReceivedMessage = """🍯 %s wysyła Ci %d sat."""
inlineTipjarHelpTipjarInGroup = """Stwórz w grupie z tym botem słoik na napiwki (_tipjar_) lub użyj 👉 komendy inline (zobacz /advanced aby uzyskać więcej informacji)."""
inlineTipjarHelpText = """📖 Ojej, to nie zadziałało. %s
*Użycie:* `/tipjar <capacity> <na_użytkownika>`
*Przykład:* `/tipjar 210 21`"""
# GROUP TICKETS
groupAddGroupHelpMessage = """📖 Ojej, to nie zadziałało. Ta komenda działa tylko w chacie grupowym. Tylko właściciele grupy mogą użyć tej komendy.\nUżycie: `/group add <nazwa_grupy> [<kwota>]`\nPrzykład: `/group add NajlepszaGrupaBitcoinowa 1000`"""
groupJoinGroupHelpMessage = """📖 Ojej, to nie zadziałało. Spróbuj ponownie później.\nUżycie: `/join <nazwa_grupy>`\nPrzykład: `/join NajlepszaGrupaBitcoinowa`"""
groupClickToJoinMessage = """🎟 [Kliknij tu](%s) 👈 aby dołączyć do `%s`."""
groupTicketIssuedGroupMessage = """🎟 Użytkownik %s otrzymuje bilet do tej grupy."""
groupPayInvoiceMessage = """🎟 Aby dołączyć do grupy %s, opłać powyższą fakturę."""
groupBotIsNotAdminMessage = """🚫 Ojej, to nie zadziałało. Musisz uczynić mnie administratorem i nadać prawo do zapraszania użytkowników."""
groupNameExists = """🚫 Grupa o tej nazwie już istnieje. Wybierz inną nazwę."""
groupAddedMessage = """🎟 Bilety dla grupy `%s` dodane.\nAlias: `%s` Cena: %d sat\n\nAby poprosić o bilet na tę grupę, rozpocznij prywatny czat z %s i napisz `/join %s`."""
groupNotFoundMessage = """🚫 Nie znaleziono grupy o tej nazwie."""
groupReceiveTicketInvoiceCommission = """🎟 Otrzymujesz *%d sat* (wyłączając. %d sat prowizji) za bilet na grupę `%s` zapłacony przez %s."""
groupReceiveTicketInvoice = """🎟 Otrzymujesz *%d sat* za bilet na grupę `%s` zapłacony przez %s."""
commandPrivateMessage = """Użyj proszę tej komendy na czacie prywatnym z %s."""
groupHelpMessage = """🎟 Bilety na prywatne grupy 🎟
Sprzedawaj bilety na swoją _prywatną grupę_ i pozbądź się spamujących botów.
*Instrukcje dla administratorów grup:*
1) Zaproś %s do swojej grupy i nadaj uprawnienia administratora.
2) Uczyń swoją grupę prywatną.
3) W grupie, napisz (będąc właścicielem grupy) napisz `/group add <mojagrupa> [<cena_biletu>]`.
_Opłaty: Bot bierze prowizję w wysokości 10%% + 10 sat za tanie bilety. Jeśli cena bilety >= 1000 sat, prowizja wynosi 2%% + 100 sat._
*Instrukcje dla członków grupy:*
Aby dołączyć do grupy, napisz do %s i napisz w prywatnej wiadomości `/join <mojagrupa>`.
📖 *Użycie:*
*Dla adminów (w czacie grupowym):* `/group add <nazwa_grupy> [<cena_biletu>]`\nPrzykład: `/group add NajlepszaGrupaBitcoinowa 1000`
*Dla użytkowników (w czacie prywatnym):* `/join <nazwa_grupy>`\nPrzykład: `/join NajlepszaGrupaBitcoinowa`"""
# DALLE GENERATE
generateDalleHelpMessage = """Generuj obrazy przy użyciu OpenAI DALLE 2.\nUżycie: `/generate <podpowiedź>`\nCena: 1000 sat"""
generateDallePayInvoiceMessage = """Opłać tę fakturę by wygenerować 4 obrazy 👇"""
generateDalleGeneratingMessage = """Twoje obrazy są generowane. Proszę czekaj..."""
+5 -2
View File
@@ -119,11 +119,13 @@ advancedMessage = """%s
⚙️ *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>`
*/lnurl* ⚡️ Receber ou pagar com lnurl: `/lnurl` o `/lnurl <lnurl> [memo]`
*/nostr* 💜 Connect to Nostr: `/nostr`
*/faucet* 🚰 Criar uma torneira: `/faucet <capacidade> <por_usuário>`
*/tipjar* 🍯 Criar uma tipjar: `/tipjar <capacidade> <por_usuário>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`"""
*/shop* 🛍 Browse shops: `/shop` or `/shop <user/shop_id>`
*/generate* 🎆 Generate DALLE-2 images: `/generate <prompt>`"""
# GENERIC
enterAmountRangeMessage = """💯 Insira uma quantia entre %d e %d sat."""
@@ -182,6 +184,7 @@ sendHelpText = """📖 Opa, isso não funcionou. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Recebeu %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Recebeu %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Você inseriu uma quantia?"""
invoiceValidAmountMessage = """Você inseriu uma quantia válida?"""
invoiceHelpText = """📖 Opa, isso não funcionou. %s
+3 -1
View File
@@ -123,7 +123,8 @@ advancedMessage = """%s
⚙️ *Продвинутые команды*
*/transactions* 📊 List transactions
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
*/lnurl* Получить или оплатить через ⚡️Lnurl: `/lnurl` or `/lnurl <lnurl>`
*/lnurl* Получить или оплатить через ⚡️Lnurl: `/lnurl` or `/lnurl <lnurl> [memo]`
*/nostr* 💜 Connect to Nostr: `/nostr`
*/faucet* 🚰 Создать криптораздачу: `/faucet <ёмкость> <на_пользователя>`
*/tipjar* 🍯 Создать копилку: `/tipjar <ёмкость> <на_пользователя>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
@@ -186,6 +187,7 @@ sendHelpText = """📖 Упс, это не сработало. %s
# INVOICE
invoiceReceivedMessage = """⚡️ Вы получили %d sat."""
invoiceReceivedCurrencyMessage = """⚡️ Вы получили %d sat (%.2f %s)."""
invoiceEnterAmountMessage = """Ввели ли вы сумму?"""
invoiceValidAmountMessage = """Ввели ли вы правильную сумму?"""
invoiceHelpText = """📖 Упс, это не сработало. %s
+3 -1
View File
@@ -119,7 +119,8 @@ advancedMessage = """%s
⚙️ *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>`
*/lnurl* ⚡️ Lnurl iste veya gönder: `/lnurl` veya `/lnurl <lnurl> [memo]`
*/nostr* 💜 Connect to Nostr: `/nostr`
*/faucet* 🚰 Bir fıçı oluştur: `/faucet <toplam> <kullanıcı_başına>`
*/tipjar* 🍯 Bir tipjar oluştur: `/tipjar <capacity> <per_user>`
*/group* 🎟 Create group tickets: `/group add <mygroup> [<ticket_price>]`
@@ -182,6 +183,7 @@ sendHelpText = """📖 Hoppalaa… olmadı. %s
# INVOICE
invoiceReceivedMessage = """⚡️ %d sat sana geldi."""
invoiceReceivedCurrencyMessage = """⚡️ %d sat (%.2f %s) sana geldi."""
invoiceEnterAmountMessage = """Miktar girdin mi?"""
invoiceValidAmountMessage = """Geçerli bir miktar girdin mi?"""
invoiceHelpText = """📖 Hoppalaa… olmadı. %s