Compare commits

...
66 Commits
Author SHA1 Message Date
gohumble 0d2814d45c fix typo 2022-03-01 10:24:33 +01:00
gohumble c9b26641ea ⏱ Add Mutex with TTL 2022-03-01 10:19:18 +01:00
gohumbleandGitHub a9f6539eaf 🪄 fix LNURL states redundant initialization (#318) 2022-02-27 15:33:04 +03:00
gohumbleandGitHub 1179800a4b 🪄 fix withdraw state handler (#316) 2022-02-26 10:53:15 +03:00
calleandGitHub a5d8c5d7e5 lnurl amounts same (#315) 2022-02-25 14:11:05 +03:00
0dcf4bd845 fix the tipjar and send a summary (#312)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-17 17:14:25 +01:00
afcbca28f2 faucet md (#309)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-14 20:44:34 +01:00
calleandGitHub 205e75d2d6 markdown fix (#308) 2022-02-11 13:24:03 +01:00
calleandGitHub 6e7886e029 payerdata hash fix (#307) 2022-02-11 12:56:30 +01:00
00b07998e6 Payerdata receive (#306)
* payerdata receive

* more

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-11 12:40:18 +01:00
calleandGitHub 373b4a9752 payerdata receive (#305) 2022-02-11 12:16:46 +01:00
fa46f06f2e resize image (#304)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-11 10:52:57 +01:00
24e321e5ed bot pic (#303)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-11 10:47:40 +01:00
725af545ab WIP: adding downloadMyProfilePicture and botProfilePicture to LNURL Meta (#297)
* adding downloadMyProfilePicture and botProfilePicture to serveLNURLFirst (pay)

* fix image download to ram

* add downloadProfilePicture

* add cache and download limit

* error checks

* user picture

* empty entry bug check for uuid

* check

* fix example

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-11 10:04:08 +01:00
2b09fc95dd print debug stack on empty annon id update (#299)
* print debug stack on empty annon id update

* write stack to file

* use AnnonID

* set ids

* comments

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-07 22:12:03 +01:00
54beceba32 add empty callback response (#301)
* add empty response

* commend

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-07 22:03:17 +01:00
70ecf335f2 honkhonk (#302)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-02-07 21:30:02 +01:00
d786dc58e0 Unban fix (#300)
* unban fix

* fix

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-30 20:41:12 +01:00
c72111dfb7 add (#296)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-23 00:57:17 +01:00
902928f794 perform graceful shutdown on SIGTERM and SIGSTOP (#281)
* perform graceful shutdown on SIGTERM and SIGSTOP

* comments

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-23 00:48:27 +01:00
96292604c7 adding lnurl auth (#294)
* adding lnurl auth poc

* add response and translation

* refactor

* simpler

* using http bot client with proxy transport

* functions

* translations

* clean

* comment

* revert

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-22 23:25:21 +01:00
9522418272 finish faucet (#295)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-22 14:04:48 +01:00
a112c1b25d add shop db path (#292)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-19 11:25:37 +01:00
72e13e841d faucet fix (#291)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-15 02:11:25 +01:00
83eb185634 echo fix (#290)
* echo fix

* echo fix

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-15 01:11:11 +01:00
dedc959f94 faucet summary (#289)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-15 00:58:59 +01:00
33776f2616 oops (#288)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-14 20:38:45 +01:00
545d20d043 Mutex fix 329823hf (#287)
* big change

* mutex

* global lock

* another lock

* fix log

* trySendMessageEditable added

* defer before return

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-14 20:34:20 +01:00
9d876cf5d5 stuck fix (#286)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-12 12:26:22 +01:00
c6087021b7 fix again (#285)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-12 12:20:00 +01:00
7c95daabfd shop stuck fix (#284)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-12 12:16:47 +01:00
95a22401b2 shop logging (#283)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-11 00:44:07 +01:00
a7b9506a9f better log (#282)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-11 00:34:59 +01:00
c1fb07fcda mutex return (#280)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-09 23:44:06 +01:00
5a25f07bfb callback responses (#279)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-09 22:20:42 +01:00
b6d1ed97f1 failsaves (#278)
* failsaves

* failsafe2

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-09 21:43:02 +01:00
4e812f7897 add errors to handler (#273)
* add errors to handler

* add errors to handlers

* shop fixes (#274)

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

* better log (#275)

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

* add errors to map

* more errors

* rename NoWalletError

* fix one panic (#276)

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

* add invalid type error

* Shop panic attempt 2 (#277)

* less log

* fix shop first view

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

* make errors private

* add errors to handler

* add errors to handlers

* add errors to map

* more errors

* rename NoWalletError

* add invalid type error

* make errors private

* patch

* return handlers

* add noPrivateChat

* add invalid amount err

Co-authored-by: LightningTipBot <88730856+LightningTipBot@users.noreply.github.com>
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-09 21:39:09 +01:00
192930a289 Shop panic attempt 2 (#277)
* less log

* fix shop first view

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-09 20:01:26 +01:00
7ed34f656b fix one panic (#276)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-09 19:52:18 +01:00
31250273b0 better log (#275)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-09 12:16:05 +01:00
e70344892f shop fixes (#274)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-09 11:08:27 +01:00
39c727d3c4 fix the keyboard, fix the world (#272)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-07 12:13:58 +01:00
02eb0716aa lil update (#270)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-06 10:39:25 +01:00
c706ed7aaf update edit stack (#269)
* update edit stack

* update faucet

* better debug logging

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-06 10:33:01 +01:00
8c41fba277 no edit stack (#268)
* no edit stack

* fix typo

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-05 22:05:18 +01:00
53c384834a lnurl update (#267)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-05 10:14:24 +01:00
1e66dd6a68 fix auth (#266)
* fix auth

* comments

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-05 02:32:39 +01:00
gohumbleandGitHub b42a9ae8b4 using UpdateUserRecord (#265) 2022-01-05 01:53:45 +01:00
88143b9a66 fix migration (#264)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-05 01:43:33 +01:00
8f60cb82f3 add admin service (#263)
* add admin server + service

* string fixes

* ban and unban user

* add return

* ban using admin key

* ban reason

* remove redundant func call

* add http status

* add log

* anon_id_sha256 (#262)

* anon_id_sha256

* refactor sha256 hash to strings package

* oops

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

* add admin server + service

* ban and unban user

* string fixes

* add return

* ban using admin key

* ban reason

* remove redundant func call

* add http status

* add log

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
Co-authored-by: LightningTipBot <88730856+LightningTipBot@users.noreply.github.com>
2022-01-05 01:40:37 +01:00
e275b8760a anon_id_sha256 (#262)
* anon_id_sha256

* refactor sha256 hash to strings package

* oops

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-05 01:28:17 +01:00
gohumbleandGitHub 01710f3385 separate lnurl and api server (#261)
* separate lnurl and api server

* add lndhub handler and proxy

* update proxy

* fix AppendRoute with empty methods

* add logs

* fix trace

* dump request

* parse bearer token

* exclude banned users

* exclude banned users

* fix log levels
2022-01-05 00:09:11 +01:00
ec319cc691 fix ban (#260)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-04 13:49:31 +01:00
c6a064b332 Banned entirely (#259)
* do not react to banned users

* do not respond to banned

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-04 13:32:10 +01:00
615b90ab63 print banned (#258)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-04 12:56:38 +01:00
a7cf6f957e edit stack fix (#257)
Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2022-01-01 22:26:56 +01:00
e9da937c75 Hotfix edit bug (#256)
* fix edit bug and log faucet better

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-29 22:17:59 +01:00
d0da1560fa New logo (#255)
* speed up tx lock

* yolo master

* upload new logo

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-29 11:13:24 +01:00
113fc02b28 Faucet problem 123 (#254)
* speed up tx lock

* yolo master

* logging

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-29 11:04:17 +01:00
1459fcb68e Fix link delete message (#253)
* fix

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-28 15:09:45 +01:00
3d3d7ab2f6 Send keyboard recommendation (#252)
* speed up tx lock

* yolo master

* keyboard with recent contacts

* translate message

* better query

* keyboard pops up

* log level

* skip keyboard if no entry

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-28 12:20:47 +01:00
fdb58a7f2b Fix faucet again (#251)
* speed up tx lock

* yolo master

* fix faucet again

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-27 19:13:07 +01:00
a9fecc1e8f Fix faucet again 123 (#250)
* speed up tx lock

* yolo master

* skip edit error

* do not return

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-27 18:48:58 +01:00
d65d6aad28 Fix faucet edit (#249)
* speed up tx lock

* yolo master

* better printing

* trace

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-27 18:31:25 +01:00
95c733459d Fix faucet edit (#248)
* speed up tx lock

* yolo master

* better printing

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-27 18:28:06 +01:00
9fe0d776c7 Mini fixes123 (#247)
* speed up tx lock

* yolo master

* fixes

Co-authored-by: callebtc <93376500+callebtc@users.noreply.github.com>
2021-12-26 23:37:46 +01:00
67 changed files with 2240 additions and 863 deletions
+3 -1
View File
@@ -2,6 +2,7 @@ bot:
http_proxy: ""
lnurl_public_host_name: "mylnurl.com"
lnurl_server: "https://mylnurl.com"
lnurl_image: true
telegram:
message_dispose_duration: 10
api_key: "1234"
@@ -14,4 +15,5 @@ lnbits:
database:
db_path: "data/bot.db"
buntdb_path: "data/bunt.db"
transactions_path: "data/transactions.db"
transactions_path: "data/transactions.db"
shop_buntdb_path: "data/shop.db"
+2
View File
@@ -4,6 +4,7 @@ go 1.15
require (
github.com/BurntSushi/toml v0.3.1
github.com/btcsuite/btcd v0.20.1-beta.0.20200515232429-9f0179fd2c46 // indirect
github.com/eko/gocache v1.2.0
github.com/fiatjaf/go-lnurl v1.8.4
github.com/fiatjaf/ln-decodepay v1.1.0
@@ -11,6 +12,7 @@ require (
github.com/imroc/req v0.3.0
github.com/jinzhu/configor v1.2.1
github.com/makiuchi-d/gozxing v0.0.2
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect
github.com/nicksnyder/go-i18n/v2 v2.1.2
github.com/orcaman/concurrent-map v1.0.0
github.com/patrickmn/go-cache v2.1.0+incompatible
+4
View File
@@ -83,6 +83,7 @@ github.com/btcsuite/snappy-go v1.0.0 h1:ZxaA6lo2EpxGddsA8JwWOcxlzRybb444sgmeJQMJ
github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc=
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792 h1:R8vQdOQdZ9Y3SkEwmHoWBmX1DNXhXZqlTpq6s4tyJGc=
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY=
github.com/btcsuite/winsvc v1.0.0 h1:J9B4L7e3oqhXOcm+2IuNApwzQec85lE+QaikUcCs+dk=
github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs=
github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ=
github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4=
@@ -259,6 +260,7 @@ github.com/jackpal/gateway v1.0.5/go.mod h1:lTpwd4ACLXmpyiCTRtfiNyVnUmqT9RivzCDQ
github.com/jackpal/go-nat-pmp v0.0.0-20170405195558-28a68d0c24ad/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc=
github.com/jedib0t/go-pretty v4.3.0+incompatible/go.mod h1:XemHduiw8R651AF9Pt4FwCTKeG3oo7hrHJAoznj9nag=
github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/jessevdk/go-flags v1.4.0 h1:4IU2WS7AumrZ/40jfhf4QVDMsQwqA7VEHozFRrGARJA=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/jinzhu/configor v1.2.1 h1:OKk9dsR8i6HPOCZR8BcMtcEImAFjIhbJFZNyn5GCZko=
github.com/jinzhu/configor v1.2.1/go.mod h1:nX89/MOmDba7ZX7GCyU/VIaQ2Ar2aizBl2d3JLF/rDc=
@@ -363,6 +365,8 @@ github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzE
github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
github.com/nicksnyder/go-i18n/v2 v2.1.2 h1:QHYxcUJnGHBaq7XbvgunmZ2Pn0focXFqTD61CkH146c=
github.com/nicksnyder/go-i18n/v2 v2.1.2/go.mod h1:d++QJC9ZVf7pa48qrsRWhMJ5pSHIPmS3OLqK1niyLxs=
github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78=
+15
View File
@@ -0,0 +1,15 @@
package admin
import (
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
)
type Service struct {
bot *telegram.TipBot
}
func New(b *telegram.TipBot) Service {
return Service{
bot: b,
}
}
+76
View File
@@ -0,0 +1,76 @@
package admin
import (
"fmt"
"net/http"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
func (s Service) UnbanUser(w http.ResponseWriter, r *http.Request) {
user, err := s.getUserByTelegramId(r)
if err != nil {
log.Errorf("[ADMIN] could not ban user: %v", err)
w.WriteHeader(http.StatusBadRequest)
return
}
if !user.Banned && !strings.HasPrefix(user.Wallet.Adminkey, "banned_") {
log.Infof("[ADMIN] user is not banned. Aborting.")
w.WriteHeader(http.StatusBadRequest)
return
}
user.Banned = false
adminSlice := strings.Split(user.Wallet.Adminkey, "_")
user.Wallet.Adminkey = adminSlice[len(adminSlice)-1]
err = telegram.UpdateUserRecord(user, *s.bot)
if err != nil {
log.Errorf("[ADMIN] could not update user: %v", err)
return
}
log.Infof("[ADMIN] Unbanned user (%s)", user.ID)
w.WriteHeader(http.StatusOK)
}
func (s Service) BanUser(w http.ResponseWriter, r *http.Request) {
user, err := s.getUserByTelegramId(r)
if err != nil {
log.Errorf("[ADMIN] could not ban user: %v", err)
w.WriteHeader(http.StatusBadRequest)
return
}
if user.Banned {
w.WriteHeader(http.StatusBadRequest)
log.Infof("[ADMIN] user is already banned. Aborting.")
return
}
user.Banned = true
if reason := r.URL.Query().Get("reason"); reason != "" {
user.Wallet.Adminkey = fmt.Sprintf("%s_%s", reason, user.Wallet.Adminkey)
}
user.Wallet.Adminkey = fmt.Sprintf("%s_%s", "banned", user.Wallet.Adminkey)
err = telegram.UpdateUserRecord(user, *s.bot)
if err != nil {
log.Errorf("[ADMIN] could not update user: %v", err)
return
}
log.Infof("[ADMIN] Banned user (%s)", user.ID)
w.WriteHeader(http.StatusOK)
}
func (s Service) getUserByTelegramId(r *http.Request) (*lnbits.User, error) {
user := &lnbits.User{}
v := mux.Vars(r)
if v["id"] == "" {
return nil, fmt.Errorf("invalid id")
}
tx := s.bot.Database.Where("telegram_id = ? COLLATE NOCASE", v["id"]).First(user)
if tx.Error != nil {
return nil, tx.Error
}
return user, nil
}
+25
View File
@@ -0,0 +1,25 @@
package api
import (
"net/http"
"net/http/httputil"
log "github.com/sirupsen/logrus"
)
func LoggingMiddleware(prefix string, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Tracef("[%s] %s %s", prefix, r.Method, r.URL.Path)
log.Tracef("[%s]\n%s", prefix, dump(r))
r.BasicAuth()
next.ServeHTTP(w, r)
}
}
func dump(r *http.Request) string {
x, err := httputil.DumpRequest(r, true)
if err != nil {
return ""
}
return string(x)
}
+72
View File
@@ -0,0 +1,72 @@
package api
import (
"fmt"
log "github.com/sirupsen/logrus"
"io"
"net/http"
"net/url"
"time"
)
func Proxy(wr http.ResponseWriter, req *http.Request, rawUrl string) error {
client := &http.Client{Timeout: time.Second * 10}
//http: Request.RequestURI can't be set in client requests.
//http://golang.org/src/pkg/net/http/client.go
req.RequestURI = ""
u, err := url.Parse(rawUrl)
if err != nil {
http.Error(wr, "Server Error", http.StatusInternalServerError)
log.Println("ServeHTTP:", err)
return err
}
req.URL.Host = u.Host
req.URL.Scheme = u.Scheme
req.Host = req.URL.Host
resp, err := client.Do(req)
if err != nil {
http.Error(wr, "Server Error", http.StatusInternalServerError)
log.Println("ServeHTTP:", err)
return err
}
defer resp.Body.Close()
log.Tracef("[Proxy] Proxy request status: %s", resp.Status)
if resp.StatusCode > 300 {
return fmt.Errorf("invalid response")
}
delHopHeaders(resp.Header)
copyHeader(wr.Header(), resp.Header)
wr.WriteHeader(resp.StatusCode)
_, err = io.Copy(wr, resp.Body)
return err
}
// Hop-by-hop headers. These are removed when sent to the backend.
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
var hopHeaders = []string{
"Connection",
"Keep-Alive",
"Proxy-Authenticate",
"Proxy-Authorization",
"Te", // canonicalized version of "TE"
"Trailers",
"Transfer-Encoding",
"Upgrade",
}
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
func delHopHeaders(header http.Header) {
for _, h := range hopHeaders {
header.Del(h)
}
}
+66
View File
@@ -0,0 +1,66 @@
package api
import (
"encoding/json"
"net/http"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
type Server struct {
httpServer *http.Server
router *mux.Router
}
const (
StatusError = "ERROR"
StatusOk = "OK"
)
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,
}
apiServer := &Server{
httpServer: srv,
}
apiServer.router = mux.NewRouter()
apiServer.httpServer.Handler = apiServer.router
go apiServer.httpServer.ListenAndServe()
log.Infof("[LNURL] Server started at %s", internal.Configuration.Bot.LNURLServerUrl.Host)
return apiServer
}
func (w *Server) ListenAndServe() {
go w.httpServer.ListenAndServe()
}
func (w *Server) PathPrefix(path string, handler http.Handler) {
w.router.PathPrefix(path).Handler(handler)
}
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 {
r.Methods(methods...)
}
}
func NotFoundHandler(writer http.ResponseWriter, err error) {
log.Errorln(err)
// return 404 on any error
http.Error(writer, "404 page not found", http.StatusNotFound)
}
func WriteResponse(writer http.ResponseWriter, response interface{}) error {
jsonResponse, err := json.Marshal(response)
if err != nil {
return err
}
_, err = writer.Write(jsonResponse)
return err
}
+1
View File
@@ -22,6 +22,7 @@ type BotConfiguration struct {
LNURLServerUrl *url.URL `yaml:"-"`
LNURLHostName string `yaml:"lnurl_public_host_name"`
LNURLHostUrl *url.URL `yaml:"-"`
LNURLSendImage bool `yaml:"lnurl_image"`
}
type TelegramConfiguration struct {
+39 -3
View File
@@ -9,15 +9,51 @@ import (
"gorm.io/gorm"
)
func MigrateAnonIdHash(db *gorm.DB) error {
func MigrateAnonIdInt32Hash(db *gorm.DB) error {
users := []lnbits.User{}
_ = db.Find(&users)
for _, u := range users {
log.Info(u.ID, str.Int32Hash(u.ID))
log.Infof("[MigrateAnonIdInt32Hash] %d -> %d", u.ID, str.Int32Hash(u.ID))
u.AnonID = fmt.Sprint(str.Int32Hash(u.ID))
tx := db.Save(u)
if tx.Error != nil {
errmsg := fmt.Sprintf("[MigrateAnonIdHash] Error: Couldn't migrate user %s (%d)", u.Telegram.Username, u.Telegram.ID)
errmsg := fmt.Sprintf("[MigrateAnonIdInt32Hash] Error: Couldn't migrate user %s (%d)", u.Telegram.Username, u.Telegram.ID)
log.Errorln(errmsg)
return tx.Error
}
}
return nil
}
func MigrateAnonIdSha265Hash(db *gorm.DB) error {
users := []lnbits.User{}
_ = db.Find(&users)
for _, u := range users {
pw := u.Wallet.ID
anon_id := str.AnonIdSha256(&u)
log.Infof("[MigrateAnonIdSha265Hash] %s -> %s", pw, anon_id)
u.AnonIDSha256 = anon_id
tx := db.Save(u)
if tx.Error != nil {
errmsg := fmt.Sprintf("[MigrateAnonIdSha265Hash] Error: Couldn't migrate user %s (%s)", u.Telegram.Username, pw)
log.Errorln(errmsg)
return tx.Error
}
}
return nil
}
func MigrateUUIDSha265Hash(db *gorm.DB) error {
users := []lnbits.User{}
_ = db.Find(&users)
for _, u := range users {
pw := u.Wallet.ID
uuid := str.UUIDSha256(&u)
log.Infof("[MigrateUUIDSha265Hash] %s -> %s", pw, uuid)
u.UUID = uuid
tx := db.Save(u)
if tx.Error != nil {
errmsg := fmt.Sprintf("[MigrateUUIDSha265Hash] Error: Couldn't migrate user %s (%s)", u.Telegram.Username, pw)
log.Errorln(errmsg)
return tx.Error
}
+9 -12
View File
@@ -1,20 +1,17 @@
package errors
import "encoding/json"
type TipBotErrorType int
const (
DecodeAmountError TipBotErrorType = 1000 + iota
DecodePerUserAmountError
InvalidAmountError
InvalidAmountPerUserError
GetBalanceError
BalanceToLowError
import (
"encoding/json"
)
func Create(code TipBotErrorType) TipBotError {
return errMap[code]
}
func New(code TipBotErrorType, err error) TipBotError {
return TipBotError{Err: err, Message: err.Error(), Code: code}
if err != nil {
return TipBotError{Err: err, Message: err.Error(), Code: code}
}
return Create(code)
}
type TipBotError struct {
+75
View File
@@ -0,0 +1,75 @@
package errors
import "fmt"
type TipBotErrorType int
const (
UnknownError TipBotErrorType = iota
NoReplyMessageError
InvalidSyntaxError
MaxReachedError
NoPhotoError
NoFileFoundError
NotActiveError
InvalidTypeError
)
const (
UserNoWalletError TipBotErrorType = 2000 + iota
BalanceToLowError
SelfPaymentError
NoPrivateChatError
GetBalanceError
DecodeAmountError
DecodePerUserAmountError
InvalidAmountError
InvalidAmountPerUserError
)
const (
NoShopError TipBotErrorType = 3000 + iota
NotShopOwnerError
ShopNoOwnerError
ItemIdMismatchError
)
var errMap = map[TipBotErrorType]TipBotError{
UserNoWalletError: userNoWallet,
NoReplyMessageError: noReplyMessage,
InvalidSyntaxError: invalidSyntax,
InvalidAmountPerUserError: invalidAmount,
InvalidAmountError: invalidAmountPerUser,
NoPrivateChatError: noPrivateChat,
ShopNoOwnerError: shopNoOwner,
NotShopOwnerError: notShopOwner,
MaxReachedError: maxReached,
NoShopError: noShop,
SelfPaymentError: selfPayment,
NoPhotoError: noPhoto,
ItemIdMismatchError: itemIdMismatch,
NoFileFoundError: noFileFound,
UnknownError: unknown,
NotActiveError: notActive,
InvalidTypeError: invalidType,
}
var (
userNoWallet = TipBotError{Err: fmt.Errorf("user has no wallet")}
noReplyMessage = TipBotError{Err: fmt.Errorf("no reply message")}
invalidSyntax = TipBotError{Err: fmt.Errorf("invalid syntax")}
invalidAmount = TipBotError{Err: fmt.Errorf("invalid amount")}
invalidAmountPerUser = TipBotError{Err: fmt.Errorf("invalid amount per user")}
noPrivateChat = TipBotError{Err: fmt.Errorf("no private chat")}
shopNoOwner = TipBotError{Err: fmt.Errorf("shop has no owner")}
notShopOwner = TipBotError{Err: fmt.Errorf("user is not shop owner")}
maxReached = TipBotError{Err: fmt.Errorf("maximum reached")}
noShop = TipBotError{Err: fmt.Errorf("user has no shop")}
selfPayment = TipBotError{Err: fmt.Errorf("can't pay yourself")}
noPhoto = TipBotError{Err: fmt.Errorf("no photo in message")}
itemIdMismatch = TipBotError{Err: fmt.Errorf("item id mismatch")}
noFileFound = TipBotError{Err: fmt.Errorf("no file found")}
unknown = TipBotError{Err: fmt.Errorf("unknown error")}
notActive = TipBotError{Err: fmt.Errorf("element not active")}
invalidType = TipBotError{Err: fmt.Errorf("invalid type")}
)
+46 -10
View File
@@ -1,8 +1,13 @@
package lnbits
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"time"
"github.com/btcsuite/btcd/btcec"
"github.com/imroc/req"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
@@ -15,16 +20,19 @@ type Client struct {
}
type User struct {
ID string `json:"id"`
Name string `json:"name" gorm:"primaryKey"`
Initialized bool `json:"initialized"`
Telegram *tb.User `gorm:"embedded;embeddedPrefix:telegram_"`
Wallet *Wallet `gorm:"embedded;embeddedPrefix:wallet_"`
StateKey UserStateKey `json:"stateKey"`
StateData string `json:"stateData"`
CreatedAt time.Time `json:"created"`
UpdatedAt time.Time `json:"updated"`
AnonID string `jsin:"anonid"`
ID string `json:"id"`
Name string `json:"name" gorm:"primaryKey"`
Initialized bool `json:"initialized"`
Telegram *tb.User `gorm:"embedded;embeddedPrefix:telegram_"`
Wallet *Wallet `gorm:"embedded;embeddedPrefix:wallet_"`
StateKey UserStateKey `json:"stateKey"`
StateData string `json:"stateData"`
CreatedAt time.Time `json:"created"`
UpdatedAt time.Time `json:"updated"`
AnonID string `json:"anon_id"`
AnonIDSha256 string `json:"anon_id_sha256"`
UUID string `json:"uuid"`
Banned bool `json:"banned"`
}
const (
@@ -101,3 +109,31 @@ type BitInvoice 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(
fmt.Sprintf("lnurlkeyseed:%s:%s",
domain, u.ID)))
return btcec.PrivKeyFromBytes(btcec.S256(), seedhash[:])
}
func (u User) SignKeyAuth(domain string, k1hex string) (key string, sig string, err error) {
// lnurl-auth: create a key based on the user id and sign with it
sk, pk := u.LinkingKey(domain)
k1, err := hex.DecodeString(k1hex)
if err != nil {
return "", "", fmt.Errorf("invalid k1 hex '%s': %w", k1hex, err)
}
signature, err := sk.Sign(k1)
if err != nil {
return "", "", fmt.Errorf("error signing k1: %w", err)
}
sig = hex.EncodeToString(signature.Serialize())
key = hex.EncodeToString(pk.SerializeCompressed())
return key, sig, nil
}
+68
View File
@@ -0,0 +1,68 @@
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"
)
type LndHub struct {
database *gorm.DB
}
func New(bot *telegram.TipBot) LndHub {
return LndHub{database: bot.Database}
}
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
}
+210 -48
View File
@@ -3,12 +3,22 @@ package lnurl
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/eko/gocache/store"
tb "gopkg.in/lightningtipbot/telebot.v2"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/api"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"gorm.io/gorm"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
@@ -17,20 +27,49 @@ import (
log "github.com/sirupsen/logrus"
)
type LNURLInvoice struct {
const (
PayRequestTag = "payRequest"
Endpoint = ".well-known/lnurlp"
MinSendable = 1000 // mSat
MaxSendable = 1_000_000_000
CommentAllowed = 500
)
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"`
}
type Lnurl struct {
telegram *tb.Bot
c *lnbits.Client
database *gorm.DB
callbackHostname *url.URL
buntdb *storage.DB
WebhookServer string
cache telegram.Cache
}
func (lnurlInvoice LNURLInvoice) Key() string {
func New(bot *telegram.TipBot) Lnurl {
return Lnurl{
c: bot.Client,
database: bot.Database,
callbackHostname: internal.Configuration.Bot.LNURLHostUrl,
WebhookServer: internal.Configuration.Lnbits.WebhookServer,
buntdb: bot.Bunt,
telegram: bot.Telegram,
cache: bot.Cache,
}
}
func (lnurlInvoice Invoice) Key() string {
return fmt.Sprintf("lnurl-p:%s", lnurlInvoice.PaymentHash)
}
func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
var err error
var response interface{}
username := mux.Vars(request)["username"]
@@ -39,20 +78,31 @@ func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
} else {
stringAmount := request.FormValue("amount")
if stringAmount == "" {
NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Form value 'amount' is not set"))
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Form value 'amount' is not set"))
return
}
amount, parseError := strconv.Atoi(stringAmount)
if parseError != nil {
NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int %v", parseError))
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int %v", parseError))
return
}
comment := request.FormValue("comment")
if len(comment) > CommentAllowed {
NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Comment is too long"))
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Comment is too long"))
return
}
response, err = w.serveLNURLpSecond(username, int64(amount), comment)
// 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)
}
response, err = w.serveLNURLpSecond(username, int64(amount), comment, payerData)
}
// check if error was returned from first or second handlers
if err != nil {
@@ -60,85 +110,103 @@ func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
log.Errorf("[LNURL] %v", err.Error())
if response != nil {
// there is a valid error response
err = writeResponse(writer, response)
err = api.WriteResponse(writer, response)
if err != nil {
NotFoundHandler(writer, err)
api.NotFoundHandler(writer, err)
}
}
return
}
// no error from first or second handler
err = writeResponse(writer, response)
err = api.WriteResponse(writer, response)
if err != nil {
NotFoundHandler(writer, err)
api.NotFoundHandler(writer, err)
}
}
func (w Lnurl) getMetaDataCached(username string) lnurl.Metadata {
key := fmt.Sprintf("lnurl_metadata_%s", username)
// load metadata from cache
if m, err := w.cache.Get(key); err == nil {
return m.(lnurl.Metadata)
}
// otherwise, create new metadata
metadata := w.metaData(username)
// load the user profile picture
if internal.Configuration.Bot.LNURLSendImage {
// get the user from the database
user, tx := findUser(w.database, username)
if tx.Error == nil && user.Telegram != nil {
addImageToMetaData(w.telegram, &metadata, username, user.Telegram)
}
}
// save into cache
runtime.IgnoreError(w.cache.Set(key, metadata, &store.Options{Expiration: 30 * time.Minute}))
return metadata
}
// serveLNURLpFirst serves the first part of the LNURLp protocol with the endpoint
// to call and the metadata that matches the description hash of the second response
func (w Server) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error) {
func (w Lnurl) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error) {
log.Infof("[LNURL] Serving endpoint for user %s", username)
callbackURL, err := url.Parse(fmt.Sprintf("%s/%s/%s", w.callbackHostname.String(), lnurlEndpoint, username))
callbackURL, err := url.Parse(fmt.Sprintf("%s/%s/%s", w.callbackHostname.String(), Endpoint, username))
if err != nil {
return nil, err
}
metadata := w.metaData(username)
// produce the metadata including the image
metadata := w.getMetaDataCached(username)
return &lnurl.LNURLPayParams{
LNURLResponse: lnurl.LNURLResponse{Status: statusOk},
Tag: payRequestTag,
LNURLResponse: lnurl.LNURLResponse{Status: api.StatusOk},
Tag: PayRequestTag,
Callback: callbackURL.String(),
MinSendable: minSendable,
MinSendable: MinSendable,
MaxSendable: MaxSendable,
EncodedMetadata: metadata.Encode(),
CommentAllowed: CommentAllowed,
PayerData: &lnurl.PayerDataSpec{
FreeName: &lnurl.PayerDataItemSpec{},
LightningAddress: &lnurl.PayerDataItemSpec{},
Email: &lnurl.PayerDataItemSpec{},
},
}, nil
}
// serveLNURLpSecond serves the second LNURL response with the payment request with the correct description hash
func (w Server) serveLNURLpSecond(username string, amount_msat int64, comment string) (*lnurl.LNURLPayValues, error) {
func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment string, payerData lnurl.PayerDataValues) (*lnurl.LNURLPayValues, error) {
log.Infof("[LNURL] Serving invoice for user %s", username)
if amount_msat < minSendable || amount_msat > MaxSendable {
if amount_msat < MinSendable || amount_msat > MaxSendable {
// amount is not ok
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: statusError,
Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", minSendable, MaxSendable)},
Status: api.StatusError,
Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", MinSendable, MinSendable)},
}, fmt.Errorf("amount out of bounds")
}
// check comment length
if len(comment) > CommentAllowed {
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: statusError,
Status: api.StatusError,
Reason: fmt.Sprintf("Comment too long (max: %d characters).", CommentAllowed)},
}, fmt.Errorf("comment too long")
}
// now check for the user
user := &lnbits.User{}
// check if "username" is actually the user ID
tx := w.database
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
// asume it's a user ID
tx = w.database.Where("anon_id = ?", username).First(user)
} else {
// assume it's a string @username
tx = w.database.Where("telegram_username = ? COLLATE NOCASE", username).First(user)
}
user, tx := findUser(w.database, username)
if tx.Error != nil {
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: statusError,
Status: api.StatusError,
Reason: fmt.Sprintf("Invalid user.")},
}, fmt.Errorf("[GetUser] Couldn't fetch user info from database: %v", tx.Error)
}
if user.Wallet == nil {
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: statusError,
Status: api.StatusError,
Reason: fmt.Sprintf("Invalid user.")},
}, fmt.Errorf("[serveLNURLpSecond] user %s not found", username)
}
@@ -148,11 +216,24 @@ func (w Server) serveLNURLpSecond(username string, amount_msat int64, comment st
var resp *lnurl.LNURLPayValues
// the same description_hash needs to be built in the second request
metadata := w.metaData(username)
descriptionHash, err := w.descriptionHash(metadata)
metadata := w.getMetaDataCached(username)
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
}
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Amount: amount_msat / 1000,
@@ -164,7 +245,7 @@ func (w Server) serveLNURLpSecond(username string, amount_msat int64, comment st
err = fmt.Errorf("[serveLNURLpSecond] Couldn't create invoice: %v", err.Error())
resp = &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{
Status: statusError,
Status: api.StatusError,
Reason: "Couldn't create invoice."},
}
return resp, err
@@ -174,13 +255,14 @@ func (w Server) serveLNURLpSecond(username string, amount_msat int64, comment st
PaymentHash: invoice.PaymentHash,
Amount: amount_msat / 1000,
}
// save lnurl invoice struct for later use (will hold the comment or other metdata for a notification when paid)
// save lnurl invoice struct for later use (will hold the comment or other metadata for a notification when paid)
runtime.IgnoreError(w.buntdb.Set(
LNURLInvoice{
Invoice{
Invoice: invoiceStruct,
User: user,
Comment: comment,
CreatedAt: time.Now(),
From: extractSenderFromPayerdata(payerData),
}))
// save the invoice Event that will be loaded when the invoice is paid and trigger the comment display callback
runtime.IgnoreError(w.buntdb.Set(
@@ -191,7 +273,7 @@ func (w Server) serveLNURLpSecond(username string, amount_msat int64, comment st
}))
return &lnurl.LNURLPayValues{
LNURLResponse: lnurl.LNURLResponse{Status: statusOk},
LNURLResponse: lnurl.LNURLResponse{Status: api.StatusOk},
PR: invoice.PaymentRequest,
Routes: make([]struct{}, 0),
SuccessAction: &lnurl.SuccessAction{Message: "Payment received!", Tag: "message"},
@@ -200,17 +282,97 @@ func (w Server) serveLNURLpSecond(username string, amount_msat int64, comment st
}
// descriptionHash is the SHA256 hash of the metadata
func (w Server) descriptionHash(metadata lnurl.Metadata) (string, error) {
hash := sha256.Sum256([]byte(metadata.Encode()))
hashString := hex.EncodeToString(hash[:])
func (w Lnurl) 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
}
// metaData returns the metadata that is sent in the first response
// and is used again in the second response to verify the description hash
func (w Server) metaData(username string) lnurl.Metadata {
func (w Lnurl) metaData(username string) lnurl.Metadata {
// this is a bit stupid but if the address is a UUID starting with 1x...
// 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)
if user.Telegram.Username != "" {
username = user.Telegram.Username
}
}
return lnurl.Metadata{
Description: fmt.Sprintf("Pay to %s@%s", username, w.callbackHostname.Hostname()),
LightningAddress: fmt.Sprintf("%s@%s", username, w.callbackHostname.Hostname()),
}
}
// addImageMetaData add images an image to the LNURL metadata
func addImageToMetaData(tb *tb.Bot, metadata *lnurl.Metadata, username string, user *tb.User) {
metadata.Image.Ext = "jpeg"
// if the username is anonymous, add the bot's picture
if isAnonUsername(username) {
metadata.Image.Bytes = telegram.BotProfilePicture
return
}
// if the user has a profile picture, add it
picture, err := telegram.DownloadProfilePicture(tb, user)
if err != nil {
log.Debugf("[LNURL] Couldn't download user %s's profile picture: %v", username, err)
// in case the user has no image, use bot's picture
metadata.Image.Bytes = telegram.BotProfilePicture
return
}
metadata.Image.Bytes = picture
}
func isAnonUsername(username string) bool {
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
return true
} else {
return strings.HasPrefix(username, "0x")
}
}
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
}
if payer.Email != "" {
return payer.Email
}
if payer.FreeName != "" {
return payer.FreeName
}
return ""
}
-82
View File
@@ -1,82 +0,0 @@
package lnurl
import (
"encoding/json"
"net/http"
"net/url"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
)
type Server struct {
httpServer *http.Server
bot *telegram.TipBot
c *lnbits.Client
database *gorm.DB
callbackHostname *url.URL
buntdb *storage.DB
WebhookServer string
}
const (
statusError = "ERROR"
statusOk = "OK"
payRequestTag = "payRequest"
lnurlEndpoint = ".well-known/lnurlp"
minSendable = 1000 // mSat
MaxSendable = 1_000_000_000
CommentAllowed = 500
)
func NewServer(bot *telegram.TipBot) *Server {
srv := &http.Server{
Addr: internal.Configuration.Bot.LNURLServerUrl.Host,
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
apiServer := &Server{
c: bot.Client,
database: bot.Database,
bot: bot,
httpServer: srv,
callbackHostname: internal.Configuration.Bot.LNURLHostUrl,
WebhookServer: internal.Configuration.Lnbits.WebhookServer,
buntdb: bot.Bunt,
}
apiServer.httpServer.Handler = apiServer.newRouter()
go apiServer.httpServer.ListenAndServe()
log.Infof("[LNURL] Server started at %s", internal.Configuration.Bot.LNURLServerUrl.Host)
return apiServer
}
func (w *Server) newRouter() *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/.well-known/lnurlp/{username}", w.handleLnUrl).Methods(http.MethodGet)
router.HandleFunc("/@{username}", w.handleLnUrl).Methods(http.MethodGet)
return router
}
func NotFoundHandler(writer http.ResponseWriter, err error) {
log.Errorln(err)
// return 404 on any error
http.Error(writer, "404 page not found", http.StatusNotFound)
}
func writeResponse(writer http.ResponseWriter, response interface{}) error {
jsonResponse, err := json.Marshal(response)
if err != nil {
return err
}
_, err = writer.Write(jsonResponse)
return err
}
+7
View File
@@ -17,6 +17,7 @@ var defaultTickerCoolDown = time.Second * 10
type ResettableFunctionTicker struct {
Ticker *time.Ticker
ResetChan chan struct{} // channel used to reset the ticker
StopChan chan struct{} // channel used to stop the ticker
duration time.Duration
Started bool
name string
@@ -44,6 +45,7 @@ func GetTicker(name string, option ...ResettableFunctionTickerOption) *Resettabl
func NewResettableFunctionTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
t := &ResettableFunctionTicker{
ResetChan: make(chan struct{}, 1),
StopChan: make(chan struct{}, 1),
name: name,
}
@@ -70,6 +72,11 @@ func (t *ResettableFunctionTicker) Do(f func()) {
case <-t.ResetChan:
// reset signal received. creating new ticker.
t.Ticker = time.NewTicker(t.duration)
case <-t.StopChan:
// reset signal received. creating new ticker.
t.Ticker = nil
tickerMap.Remove(t.name)
return
}
}
}()
+45 -4
View File
@@ -3,29 +3,37 @@ package mutex
import (
"context"
"fmt"
"github.com/gorilla/mux"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"net/http"
"sync"
"time"
"github.com/gorilla/mux"
cmap "github.com/orcaman/concurrent-map"
log "github.com/sirupsen/logrus"
)
var mutexMap cmap.ConcurrentMap
var mutexMapSync sync.Mutex
func init() {
mutexMap = cmap.New()
mutexMapSync = sync.Mutex{}
}
func IsEmpty() bool {
return mutexMap.Count() == 0
}
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(fmt.Sprintf("Current number of locks: %d\nLocks: %+v\nUse /mutex/unlock endpoint to unlock all users", len(mutexMap.Keys()), mutexMap.Keys())))
w.Write([]byte(fmt.Sprintf("Current number of locks: %d\nLocks: %+v\nUse /mutex/unlock/{id} endpoint to mutex", len(mutexMap.Keys()), mutexMap.Keys())))
}
func UnlockHTTP(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
if m, ok := mutexMap.Get(vars["id"]); ok {
m.(*sync.Mutex).Unlock()
w.Write([]byte(fmt.Sprintf("Unlocked %s mutexe.\nCurrent number of locks: %d\nLocks: %+v",
w.Write([]byte(fmt.Sprintf("Unlocked mutex %s.\nCurrent number of locks: %d\nLocks: %+v",
vars["id"], len(mutexMap.Keys()), mutexMap.Keys())))
return
}
@@ -50,6 +58,12 @@ func checkSoftLock(s string) int {
// nLocks in the mutexMap. If not, it locks the object. This is supposed to lock only if nLock == 0.
func LockWithContext(ctx context.Context, s string) {
uid := ctx.Value("uid").(string)
if len(uid) == 0 {
log.Error("[Mutex] LockWithContext: uid is empty!")
}
if len(s) == 0 {
log.Error("[Mutex] LockWithContext: s is empty!")
}
// sync mutex to sync checkSoftLock with the increment of nLocks
// same user can't lock the same object multiple times
Lock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
@@ -70,6 +84,14 @@ func LockWithContext(ctx context.Context, s string) {
// nLocks == 1
func UnlockWithContext(ctx context.Context, s string) {
uid := ctx.Value("uid").(string)
if len(uid) == 0 {
log.Error("[Mutex] UnlockWithContext: uid is empty!")
return
}
if len(s) == 0 {
log.Error("[Mutex] UnlockWithContext: s is empty!")
return
}
Lock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
var nLocks = checkSoftLock(uid)
nLocks--
@@ -91,23 +113,42 @@ func Lock(s string) {
log.Tracef("[Mutex] Attempt Lock %s", s)
if m, ok := mutexMap.Get(s); ok {
m.(*sync.Mutex).Lock()
// write into mutex map
mutexMapSync.Lock()
mutexMap.Set(s, m)
mutexMapSync.Unlock()
} else {
m := &sync.Mutex{}
m.Lock()
tick := runtime.NewResettableFunctionTicker(s, runtime.WithDuration(time.Hour))
tick.Do(
func() {
Unlock(s)
})
// write into mutex map
mutexMapSync.Lock()
mutexMap.Set(fmt.Sprintf("ticker_%s", s), tick)
mutexMap.Set(s, m)
mutexMapSync.Unlock()
}
log.Tracef("[Mutex] Locked %s", s)
}
// Unlock unlocks a mutex in the mutexMap.
func Unlock(s string) {
mutexMapSync.Lock()
if m, ok := mutexMap.Get(s); ok {
mutexMap.Remove(s)
tickerKey := fmt.Sprintf("ticker_%s", s)
if tick, ok := mutexMap.Get(tickerKey); ok {
tick.(*runtime.ResettableFunctionTicker).StopChan <- struct{}{}
mutexMap.Remove(tickerKey)
}
m.(*sync.Mutex).Unlock()
log.Tracef("[Mutex] Unlocked %s", s)
} else {
// this should never happen. Mutex should have been in the mutexMap.
log.Errorf("[Mutex] ⚠⚠⚠️ Unlock %s not in mutexMap. Skip.", s)
log.Errorf("[Mutex] ⚠️⚠️⚠️ Unlock %s not in mutexMap. Skip.", s)
}
mutexMapSync.Unlock()
}
+17
View File
@@ -1,9 +1,12 @@
package str
import (
"crypto/sha256"
"fmt"
"hash/fnv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
)
var markdownV2Escapes = []string{"_", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!"}
@@ -38,3 +41,17 @@ func Int64Hash(s string) uint64 {
h.Write([]byte(s))
return h.Sum64()
}
func AnonIdSha256(u *lnbits.User) string {
h := sha256.Sum256([]byte(u.Wallet.ID))
hash := fmt.Sprintf("%x", h)
anon_id := fmt.Sprintf("0x%s", hash[:16]) // starts with 0x because that can't be a valid telegram username
return anon_id
}
func UUIDSha256(u *lnbits.User) string {
h := sha256.Sum256([]byte(u.Wallet.ID))
hash := fmt.Sprintf("%x", h)
anon_id := fmt.Sprintf("1x%s", hash[len(hash)-16:]) // starts with 1x because that can't be a valid telegram username
return anon_id
}
+23 -30
View File
@@ -3,11 +3,12 @@ package telegram
import (
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
@@ -20,7 +21,7 @@ import (
func getArgumentFromCommand(input string, which int) (output string, err error) {
if len(strings.Split(input, " ")) < which+1 {
return "", errors.New("message doesn't contain enough arguments")
return "", fmt.Errorf("message doesn't contain enough arguments")
}
output = strings.Split(input, " ")[which]
return output, nil
@@ -30,7 +31,7 @@ func decodeAmountFromCommand(input string) (amount int64, err error) {
if len(strings.Split(input, " ")) < 2 {
errmsg := "message doesn't contain any amount"
// log.Errorln(errmsg)
return 0, errors.New(errmsg)
return 0, fmt.Errorf(errmsg)
}
amount, err = getAmount(strings.Split(input, " ")[1])
return amount, err
@@ -61,7 +62,7 @@ func getAmount(input string) (amount int64, err error) {
return 0, err
}
if !(price.Price[currency] > 0) {
return 0, errors.New("price is zero")
return 0, fmt.Errorf("price is zero")
}
amount = int64(fmount / price.Price[currency] * float64(100_000_000))
return amount, nil
@@ -74,7 +75,7 @@ func getAmount(input string) (amount int64, err error) {
return 0, err
}
if amount <= 0 {
return 0, errors.New("amount must be greater than 0")
return 0, fmt.Errorf("amount must be greater than 0")
}
return amount, err
}
@@ -119,15 +120,15 @@ func (bot *TipBot) askForAmount(ctx context.Context, id string, eventType string
// enterAmountHandler is invoked in anyTextHandler when the user needs to enter an amount
// the amount is then stored as an entry in the user's stateKey in the user database
// any other handler that relies on this, needs to load the resulting amount from the database
func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
user := LoadUser(ctx)
if user.Wallet == nil {
return // errors.New("user has no wallet"), 0
return ctx, errors.Create(errors.UserNoWalletError)
}
if !(user.StateKey == lnbits.UserEnterAmount) {
ResetUserState(user, bot)
return // errors.New("user state does not match"), 0
return ctx, fmt.Errorf("invalid statekey")
}
var EnterAmountStateData EnterAmountStateData
@@ -135,7 +136,7 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
if err != nil {
log.Errorf("[enterAmountHandler] %s", err.Error())
ResetUserState(user, bot)
return
return ctx, err
}
amount, err := getAmount(m.Text)
@@ -143,7 +144,7 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
log.Warnf("[enterAmountHandler] %s", err.Error())
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
ResetUserState(user, bot)
return //err, 0
return ctx, err
}
// amount not in allowed range from LNURL
if EnterAmountStateData.AmountMin > 0 && EnterAmountStateData.AmountMax >= EnterAmountStateData.AmountMin && // this line checks whether min_max is set at all
@@ -152,7 +153,7 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
log.Warnf("[enterAmountHandler] %s", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), EnterAmountStateData.AmountMin/1000, EnterAmountStateData.AmountMax/1000))
ResetUserState(user, bot)
return
return ctx, errors.Create(errors.InvalidSyntaxError)
}
// find out which type the object in bunt has waiting for an amount
@@ -164,7 +165,7 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
return
return ctx, err
}
LnurlPayState := sn.(*LnurlPayState)
LnurlPayState.Amount = amount * 1000 // mSat
@@ -175,18 +176,17 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
StateDataJson, err := json.Marshal(EnterAmountStateData)
if err != nil {
log.Errorln(err)
return
return ctx, err
}
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
bot.lnurlPayHandlerSend(ctx, m)
return
return bot.lnurlPayHandlerSend(ctx, m)
case "LnurlWithdrawState":
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(EnterAmountStateData.ID))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
return
return ctx, err
}
LnurlWithdrawState := sn.(*LnurlWithdrawState)
LnurlWithdrawState.Amount = amount * 1000 // mSat
@@ -197,35 +197,28 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
StateDataJson, err := json.Marshal(EnterAmountStateData)
if err != nil {
log.Errorln(err)
return
return ctx, err
}
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
bot.lnurlWithdrawHandlerWithdraw(ctx, m)
return
return bot.lnurlWithdrawHandlerWithdraw(ctx, m)
case "CreateInvoiceState":
m.Text = fmt.Sprintf("/invoice %d", amount)
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
bot.invoiceHandler(ctx, m)
return
return bot.invoiceHandler(ctx, m)
case "CreateDonationState":
m.Text = fmt.Sprintf("/donate %d", amount)
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
bot.donationHandler(ctx, m)
return
return bot.donationHandler(ctx, m)
case "CreateSendState":
splits := strings.SplitAfterN(EnterAmountStateData.OiringalCommand, " ", 2)
if len(splits) > 1 {
m.Text = fmt.Sprintf("/send %d %s", amount, splits[1])
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
bot.sendHandler(ctx, m)
return
return bot.sendHandler(ctx, m)
}
return
return ctx, errors.Create(errors.InvalidSyntaxError)
default:
ResetUserState(user, bot)
return
return ctx, errors.Create(errors.InvalidSyntaxError)
}
// // reset database entry
// ResetUserState(user, bot)
// return
}
+6 -6
View File
@@ -3,13 +3,14 @@ package telegram
import (
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func (bot *TipBot) balanceHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) balanceHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
// check and print all commands
if len(m.Text) > 0 {
bot.anyTextHandler(ctx, m)
@@ -23,12 +24,11 @@ func (bot *TipBot) balanceHandler(ctx context.Context, m *tb.Message) {
// first check whether the user is initialized
user := LoadUser(ctx)
if user.Wallet == nil {
return
return ctx, errors.Create(errors.UserNoWalletError)
}
if !user.Initialized {
bot.startHandler(ctx, m)
return
return bot.startHandler(ctx, m)
}
usrStr := GetUserStr(m.Sender)
@@ -36,10 +36,10 @@ func (bot *TipBot) balanceHandler(ctx context.Context, m *tb.Message) {
if err != nil {
log.Errorf("[/balance] Error fetching %s's balance: %s", usrStr, err)
bot.trySendMessage(m.Sender, Translate(ctx, "balanceErrorMessage"))
return
return ctx, err
}
log.Infof("[/balance] %s's balance: %d sat\n", usrStr, balance)
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "balanceMessage"), balance))
return
return ctx, nil
}
+52 -2
View File
@@ -2,9 +2,14 @@ package telegram
import (
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
limiter "github.com/LightningTipBot/LightningTipBot/internal/rate"
"github.com/eko/gocache/store"
@@ -81,6 +86,29 @@ func (bot TipBot) initBotWallet() error {
return nil
}
// GracefulShutdown will gracefully shutdown the bot
// It will wait for all mutex locks to unlock before shutdown.
func (bot *TipBot) GracefulShutdown() {
t := time.NewTicker(time.Second * 10)
log.Infof("[shutdown] Graceful shutdown (timeout=10s).")
for {
select {
case <-t.C:
// timer expired
log.Infof("[shutdown] Graceful shutdown timeout reached. Forcing shutdown.")
return
default:
// check if all mutex locks are unlocked
if mutex.IsEmpty() {
log.Infof("[shutdown] Graceful shutdown successful.")
return
}
}
time.Sleep(time.Second)
log.Tracef("[shutdown] Trying graceful shutdown...")
}
}
// Start will initialize the Telegram bot and lnbits.
func (bot *TipBot) Start() {
log.Infof("[Telegram] Authorized on account @%s", bot.Telegram.Me.Username)
@@ -89,9 +117,31 @@ func (bot *TipBot) Start() {
if err != nil {
log.Errorf("Could not initialize bot wallet: %s", err.Error())
}
bot.startEditWorker()
// register telegram handlers
bot.registerTelegramHandlers()
// download bot avatar once
bot.downloadMyProfilePicture()
// edit worker collects messages to edit and
// periodically edits them
bot.startEditWorker()
// register callbacks for invoices
initInvoiceEventCallbacks(bot)
// register callbacks for user state changes
initializeStateCallbackMessage(bot)
bot.Telegram.Start()
// start the telegram bot
go bot.Telegram.Start()
// 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
signal.Notify(exit, os.Interrupt, syscall.SIGTERM, syscall.SIGSTOP)
<-exit
// gracefully shutdown
bot.GracefulShutdown()
}
+31 -1
View File
@@ -1,6 +1,7 @@
package telegram
import (
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
@@ -14,6 +15,7 @@ const (
MainMenuCommandBalance = "Balance"
MainMenuCommandInvoice = "⚡️ Invoice"
MainMenuCommandHelp = "📖 Help"
SendMenuCommandEnter = "👤 Enter"
)
var (
@@ -22,6 +24,10 @@ var (
btnSendMainMenu = mainMenu.Text(MainMenuCommandSend)
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
btnInvoiceMainMenu = mainMenu.Text(MainMenuCommandInvoice)
sendToMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
sendToButtons = []tb.Btn{}
btnSendMenuEnter = mainMenu.Text(SendMenuCommandEnter)
)
func init() {
@@ -66,7 +72,7 @@ func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
if user.Wallet != nil {
amount, err := bot.GetUserBalanceCached(user)
if err == nil {
log.Debugf("[appendMainMenu] user %s balance %d sat", GetUserStr(user.Telegram), amount)
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(
@@ -77,6 +83,30 @@ func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
}
}
// makeContactsButtons will create a slice of buttons for the send menu
// it will show the 5 most recently interacted contacts and one button to use a custom contact
func (bot *TipBot) makeContactsButtons(ctx context.Context) []tb.Btn {
var records []Transaction
sendToButtons = []tb.Btn{}
user := LoadUser(ctx)
// get 5 most recent transactions by from_id with distint to_user
// where to_user starts with an @ and is not the user itself
bot.logger.Where("from_id = ? AND to_user LIKE ? AND to_user <> ?", user.Telegram.ID, "@%", GetUserStr(user.Telegram)).Distinct("to_user").Order("id desc").Limit(5).Find(&records)
log.Debugf("[makeContactsButtons] found %d records", len(records))
// 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)})
}
// add the "enter a username" button to the end
sendToButtons = append(sendToButtons, tb.Btn{Text: SendMenuCommandEnter})
sendToMenu.Reply(buttonWrapper(sendToButtons, sendToMenu, 3)...)
return sendToButtons
}
// appendMainMenu will check if to (recipient) ID is from private or group chat.
// appendMainMenu is called in telegram.go every time a user receives a PM from the bot.
// this function will only add a keyboard if this is a private chat and no force reply.
+81 -2
View File
@@ -1,11 +1,18 @@
package telegram
import (
"bufio"
"crypto/sha1"
"encoding/base64"
"fmt"
"os"
"reflect"
"runtime/debug"
"strconv"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/eko/gocache/store"
"github.com/LightningTipBot/LightningTipBot/internal"
@@ -39,16 +46,42 @@ func createBunt(file string) *storage.DB {
func ColumnMigrationTasks(db *gorm.DB) error {
var err error
// anon_id migration (2021-11-01)
if !db.Migrator().HasColumn(&lnbits.User{}, "anon_id") {
// first we need to auto migrate the user. This will create anon_id column
err = db.AutoMigrate(&lnbits.User{})
if err != nil {
panic(err)
}
log.Info("Running ano_id database migrations ...")
log.Info("Running anon_id database migrations ...")
// run the migration on anon_id
err = database.MigrateAnonIdHash(db)
err = database.MigrateAnonIdInt32Hash(db)
}
// anon_id_sha256 migration (2022-01-01)
if !db.Migrator().HasColumn(&lnbits.User{}, "anon_id_sha256") {
// first we need to auto migrate the user. This will create anon_id column
err = db.AutoMigrate(&lnbits.User{})
if err != nil {
panic(err)
}
log.Info("Running anon_id_sha256 database migrations ...")
// run the migration on anon_id
err = database.MigrateAnonIdSha265Hash(db)
}
// uuid migration (2022-02-11)
if !db.Migrator().HasColumn(&lnbits.User{}, "uuid") {
// first we need to auto migrate the user. This will create uuid column
err = db.AutoMigrate(&lnbits.User{})
if err != nil {
panic(err)
}
log.Info("Running UUID database migrations ...")
// run the migration on uuid
err = database.MigrateUUIDSha265Hash(db)
}
// todo -- add more database field migrations here in the future
return err
}
@@ -154,9 +187,55 @@ func telegramUserChanged(apiUser, stateUser *tb.User) bool {
}
return true
}
func debugStack() {
stack := debug.Stack()
go func() {
hasher := sha1.New()
hasher.Write(stack)
sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
fo, err := os.Create(fmt.Sprintf("trace_%s.txt", sha))
log.Infof("[debugStack] ⚠️ Writing stack trace to %s", fmt.Sprintf("trace_%s.txt", sha))
if err != nil {
panic(err)
}
defer func() {
if err := fo.Close(); err != nil {
panic(err)
}
}()
w := bufio.NewWriter(fo)
if _, err := w.Write(stack); err != nil {
panic(err)
}
if err = w.Flush(); err != nil {
panic(err)
}
}()
}
func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
user.UpdatedAt = time.Now()
// There is a weird bug that makes the AnonID vanish. This is a workaround.
// TODO -- Remove this after empty anon id bug is identified
if user.AnonIDSha256 == "" {
debugStack()
user.AnonIDSha256 = str.AnonIdSha256(user)
log.Errorf("[UpdateUserRecord] AnonIDSha256 empty! Setting to: %s", user.AnonIDSha256)
}
// TODO -- Remove this after empty anon id bug is identified
if user.AnonID == "" {
debugStack()
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
log.Errorf("[UpdateUserRecord] AnonID empty! Setting to: %s", user.AnonID)
}
// TODO -- Remove this after empty anon id bug is identified
if user.UUID == "" {
debugStack()
user.UUID = str.UUIDSha256(user)
log.Errorf("[UpdateUserRecord] UUID empty! Setting to: %s", user.UUID)
}
tx := bot.Database.Save(user)
if tx.Error != nil {
errmsg := fmt.Sprintf("[UpdateUserRecord] Error: Couldn't update %s's info in Database.", GetUserStr(user.Telegram))
+16 -10
View File
@@ -8,6 +8,8 @@ import (
"net/http"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
@@ -32,35 +34,35 @@ func helpDonateUsage(ctx context.Context, errormsg string) string {
}
}
func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) {
func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
// check and print all commands
bot.anyTextHandler(ctx, m)
user := LoadUser(ctx)
if user.Wallet == nil {
return
return ctx, errors.Create(errors.UserNoWalletError)
}
// if no amount is in the command, ask for it
amount, err := decodeAmountFromCommand(m.Text)
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
// // no amount was entered, set user state and ask for amount
bot.askForAmount(ctx, "", "CreateDonationState", 0, 0, m.Text)
return
_, err = bot.askForAmount(ctx, "", "CreateDonationState", 0, 0, m.Text)
return ctx, err
}
// command is valid
msg := bot.trySendMessage(m.Chat, Translate(ctx, "donationProgressMessage"))
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)))
if err != nil {
log.Errorln(err)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return
return ctx, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorln(err)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return
return ctx, err
}
// send donation invoice
@@ -72,10 +74,14 @@ func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) {
errmsg := fmt.Sprintf("[/donate] Donation failed for user %s: %s", userStr, err)
log.Errorln(errmsg)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return
return ctx, err
}
bot.tryEditMessage(msg, Translate(ctx, "donationSuccess"))
// hotfix because the edit doesn't work!
// todo: fix edit
// bot.tryEditMessage(msg, Translate(ctx, "donationSuccess"))
bot.tryDeleteMessage(msg)
bot.trySendMessage(m.Chat, Translate(ctx, "donationSuccess"))
return ctx, nil
}
func init() {
+29 -18
View File
@@ -1,17 +1,19 @@
package telegram
import (
"fmt"
"strings"
"time"
cmap "github.com/orcaman/concurrent-map"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
"time"
)
var editStack cmap.ConcurrentMap
type edit struct {
to tb.Editable
key string
what interface{}
options []interface{}
lastEdit time.Time
@@ -23,6 +25,8 @@ func init() {
}
const resultTrueError = "telebot: result is True"
const editSameStringError = "specified new message content and reply markup are exactly the same as a current content and reply markup of the message"
const retryAfterError = "retry after"
// startEditWorker will loop through the editStack and run tryEditMessage on not edited messages.
// if editFromStack is older than 5 seconds, editFromStack will be removed.
@@ -34,40 +38,47 @@ func (bot TipBot) startEditWorker() {
editFromStack := e.(edit)
if !editFromStack.edited {
_, err := bot.tryEditMessage(editFromStack.to, editFromStack.what, editFromStack.options...)
if err != nil && err.Error() != resultTrueError {
return
if err != nil && strings.Contains(err.Error(), retryAfterError) {
// ignore any other error than retry after
log.Errorf("[startEditWorker] Edit error: %s. len(editStack)=%d", err.Error(), len(editStack.Keys()))
} else {
if err != nil {
log.Errorf("[startEditWorker] Ignoring edit error: %s. len(editStack)=%d", err.Error(), len(editStack.Keys()))
}
log.Tracef("[startEditWorker] message from stack edited %+v. len(editStack)=%d", editFromStack, len(editStack.Keys()))
editFromStack.lastEdit = time.Now()
editFromStack.edited = true
editStack.Set(k, editFromStack)
}
log.Tracef("[startEditWorker] message from stack edited %+v", editFromStack)
editFromStack.lastEdit = time.Now()
editFromStack.edited = true
editStack.Set(k, editFromStack)
} else {
if editFromStack.lastEdit.Before(time.Now().Add(-(time.Duration(5) * time.Second))) {
log.Tracef("[startEditWorker] removing message edit from stack %+v", editFromStack)
log.Tracef("[startEditWorker] removing message edit from stack %+v. len(editStack)=%d", editFromStack, len(editStack.Keys()))
editStack.Remove(k)
}
}
}
}
time.Sleep(time.Second)
time.Sleep(time.Millisecond * 1000)
}
}()
}
// tryEditStack will add the editable to the edit stack, if what (message) changed.
func (bot TipBot) tryEditStack(to tb.Editable, what interface{}, options ...interface{}) {
msgSig, chat := to.MessageSig()
var sig = fmt.Sprintf("%s-%d", msgSig, chat)
if e, ok := editStack.Get(sig); ok {
func (bot TipBot) tryEditStack(to tb.Editable, key string, what interface{}, options ...interface{}) {
sig, chat := to.MessageSig()
log.Tracef("[tryEditStack] sig=%s, chat=%d, key=%s, what=%+v, options=%+v", sig, chat, key, what, options)
// var sig = fmt.Sprintf("%s-%d", msgSig, chat)
if e, ok := editStack.Get(key); ok {
editFromStack := e.(edit)
if editFromStack.what == what.(string) {
log.Tracef("[tryEditMessage] message did not change, not attempting to edit")
log.Tracef("[tryEditStack] Message already in edit stack. Skipping")
return
}
}
e := edit{options: options, what: what, to: to}
e := edit{options: options, key: key, what: what, to: to}
editStack.Set(sig, e)
editStack.Set(key, e)
log.Tracef("[tryEditStack] Added message %s to edit stack. len(editStack)=%d", key, len(editStack.Keys()))
}
+71 -47
View File
@@ -18,7 +18,6 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
@@ -82,11 +81,11 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
// // check for memo in command
memo := GetMemoFromCommand(text, 3)
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineFaucetMessage"), perUserAmount, amount, amount, 0, nTotal, MakeProgressbar(amount, amount))
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineFaucetMessage"), perUserAmount, GetUserStrMd(sender), amount, amount, 0, nTotal, MakeProgressbar(amount, amount))
if len(memo) > 0 {
inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineFaucetAppendMemo"), memo)
}
id := fmt.Sprintf("inl-faucet-%d-%d-%s", sender.ID, amount, RandStringRunes(5))
id := fmt.Sprintf("faucet:%s:%d", RandStringRunes(10), amount)
return &InlineFaucet{
Base: storage.New(storage.ID(id)),
@@ -166,11 +165,9 @@ func (bot TipBot) makeQueryFaucet(ctx context.Context, q *tb.Query, query bool)
}
func (bot TipBot) makeFaucetKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
// inlineFaucetMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
acceptInlineFaucetButton := inlineFaucetMenu.Data(Translate(ctx, "collectButtonMessage"), "confirm_faucet_inline")
cancelInlineFaucetButton := inlineFaucetMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_faucet_inline")
acceptInlineFaucetButton.Data = id
cancelInlineFaucetButton.Data = id
inlineFaucetMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
acceptInlineFaucetButton := inlineFaucetMenu.Data(Translate(ctx, "collectButtonMessage"), "confirm_faucet_inline", id)
cancelInlineFaucetButton := inlineFaucetMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_faucet_inline", id)
inlineFaucetMenu.Inline(
inlineFaucetMenu.Row(
acceptInlineFaucetButton,
@@ -179,17 +176,17 @@ func (bot TipBot) makeFaucetKeyboard(ctx context.Context, id string) *tb.ReplyMa
return inlineFaucetMenu
}
func (bot TipBot) faucetHandler(ctx context.Context, m *tb.Message) {
func (bot TipBot) faucetHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
bot.anyTextHandler(ctx, m)
if m.Private() {
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetHelpFaucetInGroup")))
return
return ctx, errors.Create(errors.NoPrivateChatError)
}
ctx = bot.mapFaucetLanguage(ctx, m.Text)
inlineFaucet, err := bot.makeFaucet(ctx, m, false)
if err != nil {
log.Warnf("[faucet] %s", err.Error())
return
return ctx, err
}
fromUserStr := GetUserStr(m.Sender)
mFaucet := bot.trySendMessage(m.Chat, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
@@ -199,15 +196,14 @@ func (bot TipBot) faucetHandler(ctx context.Context, m *tb.Message) {
if mFaucet != nil && mFaucet.Chat != nil {
log.Infof("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(mFaucet.Chat.ID, 10)[4:], mFaucet.ID)
}
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
return ctx, inlineFaucet.Set(inlineFaucet, bot.Bunt)
}
func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) (context.Context, error) {
inlineFaucet, err := bot.makeQueryFaucet(ctx, q, false)
if err != nil {
log.Errorf("[handleInlineFaucetQuery] %s", err.Error())
return
return ctx, err
}
urls := []string{
queryImage,
@@ -237,43 +233,48 @@ func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
})
if err != nil {
log.Errorln(err.Error())
return ctx, err
}
return ctx, nil
}
func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
to := LoadUser(ctx)
tx := &InlineFaucet{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Debugf("[acceptInlineFaucetHandler] %s", err.Error())
return
log.Errorf("[acceptInlineFaucetHandler] c.Data: %s, Error: %s", c.Data, err.Error())
return ctx, err
}
log.Tracef("[acceptInlineFaucetHandler] Callback c.Data: %s tx.ID: %s", c.Data, tx.ID)
inlineFaucet := fn.(*InlineFaucet)
from := inlineFaucet.From
// failsafe for queued users
if !inlineFaucet.Active {
log.Tracef(fmt.Sprintf("[faucet] faucet %s inactive. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
bot.finishFaucet(ctx, c, inlineFaucet)
return ctx, errors.Create(errors.NotActiveError)
}
// log faucet link if possible
if c.Message != nil && c.Message.Chat != nil {
log.Infof("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(c.Message.Chat.ID, 10)[4:], c.Message.ID)
}
if !inlineFaucet.Active {
log.Debugf(fmt.Sprintf("[faucet] faucet %s inactive. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
bot.finishFaucet(ctx, c, inlineFaucet)
return
}
// release faucet no matter what
if from.Telegram.ID == to.Telegram.ID {
log.Debugf("[faucet] %s is the owner faucet %s", GetUserStr(to.Telegram), inlineFaucet.ID)
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
return
ctx = context.WithValue(ctx, "callback_response", Translate(ctx, "sendYourselfMessage"))
return ctx, errors.Create(errors.SelfPaymentError)
}
// check if to user has already taken from the faucet
for _, a := range inlineFaucet.To {
if a.Telegram.ID == to.Telegram.ID {
// to user is already in To slice, has taken from facuet
log.Debugf("[faucet] %s:%d already took from faucet %s", GetUserStr(to.Telegram), to.Telegram.ID, inlineFaucet.ID)
return
ctx = context.WithValue(ctx, "callback_response", Translate(ctx, "inlineFaucetAlreadyTookMessage"))
return ctx, errors.Create(errors.UnknownError)
}
}
@@ -291,7 +292,7 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
if err != nil {
errmsg := fmt.Errorf("[faucet] Error: Could not create wallet for %s", toUserStr)
log.Errorln(errmsg)
return
return ctx, err
}
}
@@ -306,14 +307,16 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
success, err := t.Send()
if !success {
bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
// bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
errMsg := fmt.Sprintf("[faucet] Transaction failed: %s", err.Error())
log.Warnln(errMsg)
ctx = context.WithValue(ctx, "callback_response", Translate(ctx, "errorTryLaterMessage"))
// if faucet fails, cancel it:
// c.Sender.ID = inlineFaucet.From.Telegram.ID // overwrite the sender of the callback to be the faucet owner
// log.Debugf("[faucet] Canceling faucet %s...", inlineFaucet.ID)
// bot.cancelInlineFaucet(ctx, c, true) // cancel without ID check
return
bot.finishFaucet(ctx, c, inlineFaucet)
return ctx, errors.New(errors.UnknownError, err)
}
log.Infof("[💸 faucet] Faucet %s from %s to %s:%d (%d sat).", inlineFaucet.ID, fromUserStr, toUserStr, to.Telegram.ID, inlineFaucet.PerUserAmount)
@@ -321,58 +324,64 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
inlineFaucet.To = append(inlineFaucet.To, to)
inlineFaucet.RemainingAmount = inlineFaucet.RemainingAmount - inlineFaucet.PerUserAmount
go func() {
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineFaucetReceivedMessage"), fromUserStrMd, inlineFaucet.PerUserAmount))
to_message := fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineFaucetReceivedMessage"), fromUserStrMd, inlineFaucet.PerUserAmount)
ctx = context.WithValue(ctx, "callback_response", to_message)
bot.trySendMessage(to.Telegram, to_message)
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineFaucetSentMessage"), inlineFaucet.PerUserAmount, toUserStrMd))
}()
// build faucet message
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetMessage"), inlineFaucet.PerUserAmount, inlineFaucet.RemainingAmount, inlineFaucet.Amount, inlineFaucet.NTaken, inlineFaucet.NTotal, MakeProgressbar(inlineFaucet.RemainingAmount, inlineFaucet.Amount))
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetMessage"), inlineFaucet.PerUserAmount, GetUserStrMd(inlineFaucet.From.Telegram), inlineFaucet.RemainingAmount, inlineFaucet.Amount, inlineFaucet.NTaken, inlineFaucet.NTotal, MakeProgressbar(inlineFaucet.RemainingAmount, inlineFaucet.Amount))
memo := inlineFaucet.Memo
if len(memo) > 0 {
inlineFaucet.Message = inlineFaucet.Message + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetAppendMemo"), memo)
}
if inlineFaucet.UserNeedsWallet {
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStr(bot.Telegram.Me))
}
// update message
log.Infoln(inlineFaucet.Message)
// update the message if the faucet still has some sats left after this tx
if inlineFaucet.RemainingAmount >= inlineFaucet.PerUserAmount {
go func() {
bot.tryEditStack(c.Message, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
}()
bot.tryEditStack(c.Message, inlineFaucet.ID, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
}
}
if inlineFaucet.RemainingAmount < inlineFaucet.PerUserAmount {
log.Debugf(fmt.Sprintf("[faucet] faucet %s empty. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
// faucet is depleted
bot.finishFaucet(ctx, c, inlineFaucet)
}
return ctx, nil
}
func (bot *TipBot) cancelInlineFaucet(ctx context.Context, c *tb.Callback, ignoreID bool) {
func (bot *TipBot) cancelInlineFaucet(ctx context.Context, c *tb.Callback, ignoreID bool) (context.Context, error) {
tx := &InlineFaucet{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Debugf("[cancelInlineFaucetHandler] %s", err.Error())
return
return ctx, err
}
inlineFaucet := fn.(*InlineFaucet)
if ignoreID || c.Sender.ID == inlineFaucet.From.Telegram.ID {
bot.tryEditStack(c.Message, i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage"), &tb.ReplyMarkup{})
faucet_cancelled_message := i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage")
bot.tryEditStack(c.Message, inlineFaucet.ID, faucet_cancelled_message, &tb.ReplyMarkup{})
ctx = context.WithValue(ctx, "callback_response", faucet_cancelled_message)
// set the inlineFaucet inactive
inlineFaucet.Active = false
inlineFaucet.Canceled = true
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
err = inlineFaucet.Set(inlineFaucet, bot.Bunt)
if err != nil {
return ctx, err
}
log.Debugf("[faucet] Faucet %s canceled.", inlineFaucet.ID)
once.Remove(inlineFaucet.ID)
}
return
return ctx, nil
}
func (bot *TipBot) finishFaucet(ctx context.Context, c *tb.Callback, inlineFaucet *InlineFaucet) {
@@ -380,13 +389,28 @@ func (bot *TipBot) finishFaucet(ctx context.Context, c *tb.Callback, inlineFauce
if inlineFaucet.UserNeedsWallet {
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
}
bot.tryEditStack(c.Message, inlineFaucet.Message, &tb.ReplyMarkup{})
inlineFaucet.Active = false
bot.tryEditStack(c.Message, inlineFaucet.ID, inlineFaucet.Message, &tb.ReplyMarkup{})
log.Debugf("[faucet] Faucet finished %s", inlineFaucet.ID)
once.Remove(inlineFaucet.ID)
// send update to faucet creator
if inlineFaucet.Active && inlineFaucet.From.Telegram.ID != 0 {
bot.trySendMessage(inlineFaucet.From.Telegram, listFaucetTakers(inlineFaucet))
}
inlineFaucet.Active = false
}
func (bot *TipBot) cancelInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
bot.cancelInlineFaucet(ctx, c, false)
return
func listFaucetTakers(inlineFaucet *InlineFaucet) string {
var to_str string
to_str = fmt.Sprintf("🚰 *Faucet summary*\n\nMemo: %s\nCapacity: %d sat\nTakers: %d\nRemaining: %d sat\n\n*Takers:*\n\n", inlineFaucet.Memo, inlineFaucet.Amount, inlineFaucet.NTaken, inlineFaucet.RemainingAmount)
to_str += "```\n"
for _, to := range inlineFaucet.To {
to_str += fmt.Sprintf("%s\n", GetUserStr(to.Telegram))
}
to_str += "```"
return to_str
}
func (bot *TipBot) cancelInlineFaucetHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
return bot.cancelInlineFaucet(ctx, c, false)
}
+5 -4
View File
@@ -2,13 +2,14 @@ package telegram
import (
"context"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func (bot *TipBot) fileHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) fileHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
if m.Chat.Type != tb.ChatPrivate {
return
return ctx, errors.Create(errors.NoPrivateChatError)
}
user := LoadUser(ctx)
if c := stateCallbackMessage[user.StateKey]; c != nil {
@@ -26,7 +27,7 @@ func (bot *TipBot) fileHandler(ctx context.Context, m *tb.Message) {
ticker.ResetChan <- struct{}{}
}
c(ctx, m)
return
return c(ctx, m)
}
return ctx, errors.Create(errors.NoFileFoundError)
}
+55 -8
View File
@@ -21,7 +21,7 @@ func (bot TipBot) registerTelegramHandlers() {
telegramHandlerRegistration.Do(func() {
// Set up handlers
for _, h := range bot.getHandler() {
log.Debugln("registering", h.Endpoints)
log.Traceln("registering", h.Endpoints)
bot.register(h)
}
@@ -47,24 +47,24 @@ func (bot TipBot) registerHandlerWithInterceptor(h Handler) {
switch h.Interceptor.Type {
case MessageInterceptor:
for _, endpoint := range h.Endpoints {
bot.handle(endpoint, intercept.HandlerWithMessage(h.Handler.(func(ctx context.Context, query *tb.Message)),
bot.handle(endpoint, intercept.HandlerWithMessage(h.Handler.(func(ctx context.Context, query *tb.Message) (context.Context, error)),
intercept.WithBeforeMessage(h.Interceptor.Before...),
intercept.WithAfterMessage(h.Interceptor.After...),
intercept.WithDeferMessage(h.Interceptor.OnDefer...)))
}
case QueryInterceptor:
for _, endpoint := range h.Endpoints {
bot.handle(endpoint, intercept.HandlerWithQuery(h.Handler.(func(ctx context.Context, query *tb.Query)),
bot.handle(endpoint, intercept.HandlerWithQuery(h.Handler.(func(ctx context.Context, query *tb.Query) (context.Context, error)),
intercept.WithBeforeQuery(h.Interceptor.Before...),
intercept.WithAfterQuery(h.Interceptor.After...),
intercept.WithDeferQuery(h.Interceptor.OnDefer...)))
}
case CallbackInterceptor:
for _, endpoint := range h.Endpoints {
bot.handle(endpoint, intercept.HandlerWithCallback(h.Handler.(func(ctx context.Context, callback *tb.Callback)),
bot.handle(endpoint, intercept.HandlerWithCallback(h.Handler.(func(ctx context.Context, callback *tb.Callback) (context.Context, error)),
intercept.WithBeforeCallback(h.Interceptor.Before...),
intercept.WithAfterCallback(append(h.Interceptor.After, bot.answerCallbackInterceptor)...),
intercept.WithDeferCallback(h.Interceptor.OnDefer...)))
intercept.WithAfterCallback(h.Interceptor.After...),
intercept.WithDeferCallback(append(h.Interceptor.OnDefer, bot.answerCallbackInterceptor)...)))
}
}
}
@@ -120,7 +120,7 @@ func (bot TipBot) getHandler() []Handler {
},
},
{
Endpoints: []interface{}{"/tip"},
Endpoints: []interface{}{"/tip", "/t", "/honk"},
Handler: bot.tipHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
@@ -216,7 +216,7 @@ func (bot TipBot) getHandler() []Handler {
},
},
{
Endpoints: []interface{}{"/send", &btnSendMainMenu},
Endpoints: []interface{}{"/send", &btnSendMenuEnter},
Handler: bot.sendHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
@@ -232,6 +232,23 @@ func (bot TipBot) getHandler() []Handler {
},
},
},
{
Endpoints: []interface{}{&btnSendMainMenu},
Handler: bot.keyboardSendHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{
bot.localizerInterceptor,
bot.logMessageInterceptor,
bot.requireUserInterceptor,
bot.loadReplyToInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{"/faucet", "/zapfhahn", "/kraan", "/grifo"},
Handler: bot.faucetHandler,
@@ -634,6 +651,36 @@ func (bot TipBot) getHandler() []Handler {
},
},
},
{
Endpoints: []interface{}{&btnAuth},
Handler: bot.confirmLnurlAuthHandler,
Interceptor: &Interceptor{
Type: CallbackInterceptor,
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&btnCancelAuth},
Handler: bot.cancelLnurlAuthHandler,
Interceptor: &Interceptor{
Type: CallbackInterceptor,
Before: []intercept.Func{
bot.localizerInterceptor,
bot.requireUserInterceptor,
bot.lockInterceptor,
},
OnDefer: []intercept.Func{
bot.unlockInterceptor,
},
},
},
{
Endpoints: []interface{}{&shopNewShopButton},
Handler: bot.shopNewShopHandler,
+6 -6
View File
@@ -26,7 +26,7 @@ func (bot TipBot) makeHelpMessage(ctx context.Context, m *tb.Message) string {
return fmt.Sprintf(helpMessage, dynamicHelpMessage)
}
func (bot TipBot) helpHandler(ctx context.Context, m *tb.Message) {
func (bot TipBot) helpHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
// check and print all commands
bot.anyTextHandler(ctx, m)
if !m.Private() {
@@ -34,10 +34,10 @@ func (bot TipBot) helpHandler(ctx context.Context, m *tb.Message) {
bot.tryDeleteMessage(m)
}
bot.trySendMessage(m.Sender, bot.makeHelpMessage(ctx, m), tb.NoPreview)
return
return ctx, nil
}
func (bot TipBot) basicsHandler(ctx context.Context, m *tb.Message) {
func (bot TipBot) basicsHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
// check and print all commands
bot.anyTextHandler(ctx, m)
if !m.Private() {
@@ -45,7 +45,7 @@ func (bot TipBot) basicsHandler(ctx context.Context, m *tb.Message) {
bot.tryDeleteMessage(m)
}
bot.trySendMessage(m.Sender, Translate(ctx, "basicsMessage"), tb.NoPreview)
return
return ctx, nil
}
func (bot TipBot) makeAdvancedHelpMessage(ctx context.Context, m *tb.Message) string {
@@ -74,7 +74,7 @@ func (bot TipBot) makeAdvancedHelpMessage(ctx context.Context, m *tb.Message) st
)
}
func (bot TipBot) advancedHelpHandler(ctx context.Context, m *tb.Message) {
func (bot TipBot) advancedHelpHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
// check and print all commands
bot.anyTextHandler(ctx, m)
if !m.Private() {
@@ -82,5 +82,5 @@ func (bot TipBot) advancedHelpHandler(ctx context.Context, m *tb.Message) {
bot.tryDeleteMessage(m)
}
bot.trySendMessage(m.Sender, bot.makeAdvancedHelpMessage(ctx, m), tb.NoPreview)
return
return ctx, nil
}
+9 -8
View File
@@ -18,7 +18,7 @@ import (
const queryImage = "https://avatars.githubusercontent.com/u/88730856?v=4"
func (bot TipBot) inlineQueryInstructions(ctx context.Context, q *tb.Query) {
func (bot TipBot) inlineQueryInstructions(ctx context.Context, q *tb.Query) (context.Context, error) {
instructions := []struct {
url string
title string
@@ -70,6 +70,7 @@ func (bot TipBot) inlineQueryInstructions(ctx context.Context, q *tb.Query) {
if err != nil {
log.Errorln(err)
}
return ctx, err
}
func (bot TipBot) inlineQueryReplyWithError(q *tb.Query, message string, help string) {
@@ -133,10 +134,9 @@ func (bot TipBot) commandTranslationMap(ctx context.Context, command string) con
return ctx
}
func (bot TipBot) anyQueryHandler(ctx context.Context, q *tb.Query) {
func (bot TipBot) anyQueryHandler(ctx context.Context, q *tb.Query) (context.Context, error) {
if q.Text == "" {
bot.inlineQueryInstructions(ctx, q)
return
return bot.inlineQueryInstructions(ctx, q)
}
// create the inline send result
@@ -144,7 +144,7 @@ func (bot TipBot) anyQueryHandler(ctx context.Context, q *tb.Query) {
q.Text = strings.TrimPrefix(q.Text, "/")
}
if strings.HasPrefix(q.Text, "send") || strings.HasPrefix(q.Text, "pay") {
bot.handleInlineSendQuery(ctx, q)
return bot.handleInlineSendQuery(ctx, q)
}
if strings.HasPrefix(q.Text, "faucet") || strings.HasPrefix(q.Text, "zapfhahn") || strings.HasPrefix(q.Text, "kraan") || strings.HasPrefix(q.Text, "grifo") {
@@ -152,17 +152,18 @@ func (bot TipBot) anyQueryHandler(ctx context.Context, q *tb.Query) {
c := strings.Split(q.Text, " ")[0]
ctx = bot.commandTranslationMap(ctx, c)
}
bot.handleInlineFaucetQuery(ctx, q)
return bot.handleInlineFaucetQuery(ctx, q)
}
if strings.HasPrefix(q.Text, "tipjar") || strings.HasPrefix(q.Text, "spendendose") {
if len(strings.Split(q.Text, " ")) > 1 {
c := strings.Split(q.Text, " ")[0]
ctx = bot.commandTranslationMap(ctx, c)
}
bot.handleInlineTipjarQuery(ctx, q)
return bot.handleInlineTipjarQuery(ctx, q)
}
if strings.HasPrefix(q.Text, "receive") || strings.HasPrefix(q.Text, "get") || strings.HasPrefix(q.Text, "payme") || strings.HasPrefix(q.Text, "request") {
bot.handleInlineReceiveQuery(ctx, q)
return bot.handleInlineReceiveQuery(ctx, q)
}
return ctx, nil
}
+36 -29
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"strings"
"time"
@@ -40,6 +41,7 @@ type InlineReceive struct {
}
func (bot TipBot) makeReceiveKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
inlineReceiveMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
acceptInlineReceiveButton := inlineReceiveMenu.Data(Translate(ctx, "payReceiveButtonMessage"), "confirm_receive_inline")
cancelInlineReceiveButton := inlineReceiveMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_receive_inline")
acceptInlineReceiveButton.Data = id
@@ -53,16 +55,16 @@ func (bot TipBot) makeReceiveKeyboard(ctx context.Context, id string) *tb.ReplyM
return inlineReceiveMenu
}
func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) (context.Context, error) {
to := LoadUser(ctx)
amount, err := decodeAmountFromCommand(q.Text)
if err != nil {
bot.inlineQueryReplyWithError(q, Translate(ctx, "inlineQueryReceiveTitle"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
return
return ctx, err
}
if amount < 1 {
bot.inlineQueryReplyWithError(q, Translate(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
return
return ctx, errors.Create(errors.InvalidAmountError)
}
toUserStr := GetUserStr(&q.From)
@@ -82,7 +84,7 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
fmt.Sprintf(TranslateUser(ctx, "sendUserHasNoWalletMessage"), from_username),
fmt.Sprintf(TranslateUser(ctx, "inlineQueryReceiveDescription"),
bot.Telegram.Me.Username))
return
return ctx, err
}
memo_argn = 3 // assume that memo starts after the from_username
from_SpecificUser = true
@@ -140,10 +142,12 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
})
if err != nil {
log.Errorln(err)
return ctx, err
}
return ctx, nil
}
func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
// immediatelly set intransaction to block duplicate calls
mutex.LockWithContext(ctx, tx.ID)
@@ -151,12 +155,12 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callbac
rn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[getInlineReceive] %s", err.Error())
return
return ctx, err
}
inlineReceive := rn.(*InlineReceive)
if !inlineReceive.Active {
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
return
return ctx, errors.Create(errors.NotActiveError)
}
// user `from` is the one who is SENDING
@@ -166,7 +170,7 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callbac
if inlineReceive.From_SpecificUser {
if inlineReceive.From.Telegram.ID != from.Telegram.ID {
// log.Infof("User %d is not User %d", inlineReceive.From.Telegram.ID, from.Telegram.ID)
return
return ctx, errors.Create(errors.UnknownError)
}
} else {
// otherwise, we just set it to the user who has clicked
@@ -179,7 +183,7 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callbac
to := inlineReceive.To
if from.Telegram.ID == to.Telegram.ID {
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
return
return ctx, errors.Create(errors.SelfPaymentError)
}
balance, err := bot.GetUserBalance(from)
@@ -193,15 +197,15 @@ func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callbac
bot.tryEditMessage(inlineReceive.Message, inlineReceive.MessageText, &tb.ReplyMarkup{})
// runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
bot.inlineReceiveInvoice(ctx, c, inlineReceive)
return
return ctx, errors.Create(errors.BalanceToLowError)
} else {
// else, do an internal transaction
bot.sendInlineReceiveHandler(ctx, c)
return
return bot.sendInlineReceiveHandler(ctx, c)
}
}
func (bot *TipBot) sendInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) sendInlineReceiveHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
@@ -209,13 +213,13 @@ func (bot *TipBot) sendInlineReceiveHandler(ctx context.Context, c *tb.Callback)
// immediatelly set intransaction to block duplicate calls
if err != nil {
// log.Errorf("[getInlineReceive] %s", err.Error())
return
return ctx, err
}
inlineReceive := rn.(*InlineReceive)
if !inlineReceive.Active {
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
return
return ctx, errors.Create(errors.NotActiveError)
}
// defer inlineReceive.Release(inlineReceive, bot.Bunt)
@@ -230,13 +234,13 @@ func (bot *TipBot) sendInlineReceiveHandler(ctx context.Context, c *tb.Callback)
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
log.Errorln(errmsg)
return
return ctx, err
}
// check if fromUser has balance
if balance < inlineReceive.Amount {
log.Errorf("[acceptInlineReceiveHandler] balance of user %s too low", fromUserStr)
bot.trySendMessage(from.Telegram, Translate(ctx, "inlineSendBalanceLowMessage"))
return
return ctx, errors.Create(errors.BalanceToLowError)
}
// set inactive to avoid double-sends
@@ -251,12 +255,13 @@ func (bot *TipBot) sendInlineReceiveHandler(ctx context.Context, c *tb.Callback)
errMsg := fmt.Sprintf("[acceptInlineReceiveHandler] Transaction failed: %s", err.Error())
log.Errorln(errMsg)
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveFailedMessage"), &tb.ReplyMarkup{})
return
return ctx, errors.Create(errors.UnknownError)
}
log.Infof("[💸 inlineReceive] Send from %s to %s (%d sat).", fromUserStr, toUserStr, inlineReceive.Amount)
inlineReceive.Set(inlineReceive, bot.Bunt)
bot.finishInlineReceiveHandler(ctx, c)
return bot.finishInlineReceiveHandler(ctx, c)
}
func (bot *TipBot) inlineReceiveInvoice(ctx context.Context, c *tb.Callback, inlineReceive *InlineReceive) {
@@ -300,7 +305,7 @@ func (bot *TipBot) inlineReceiveEvent(invoiceEvent *InvoiceEvent) {
bot.finishInlineReceiveHandler(nil, &tb.Callback{Data: string(invoiceEvent.CallbackData)})
}
func (bot *TipBot) finishInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) finishInlineReceiveHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
// immediatelly set intransaction to block duplicate calls
mutex.LockWithContext(ctx, tx.ID)
@@ -308,7 +313,7 @@ func (bot *TipBot) finishInlineReceiveHandler(ctx context.Context, c *tb.Callbac
rn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[getInlineReceive] %s", err.Error())
return
return ctx, err
}
inlineReceive := rn.(*InlineReceive)
@@ -334,11 +339,13 @@ func (bot *TipBot) finishInlineReceiveHandler(ctx context.Context, c *tb.Callbac
if err != nil {
errmsg := fmt.Errorf("[acceptInlineReceiveHandler] Error: Receive message to %s: %s", toUserStr, err)
log.Warnln(errmsg)
return ctx, err
}
return ctx, nil
// inlineReceive.Release(inlineReceive, bot.Bunt)
}
func (bot *TipBot) cancelInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) cancelInlineReceiveHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
@@ -346,14 +353,14 @@ func (bot *TipBot) cancelInlineReceiveHandler(ctx context.Context, c *tb.Callbac
rn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[cancelInlineReceiveHandler] %s", err.Error())
return
return ctx, err
}
inlineReceive := rn.(*InlineReceive)
if c.Sender.ID == inlineReceive.To.Telegram.ID {
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveCancelledMessage"), &tb.ReplyMarkup{})
// set the inlineReceive inactive
inlineReceive.Active = false
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
if c.Sender.ID != inlineReceive.To.Telegram.ID {
return ctx, errors.Create(errors.UnknownError)
}
return
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveCancelledMessage"), &tb.ReplyMarkup{})
// set the inlineReceive inactive
inlineReceive.Active = false
return ctx, inlineReceive.Set(inlineReceive, bot.Bunt)
}
+26 -22
View File
@@ -3,6 +3,7 @@ package telegram
import (
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"strings"
"time"
@@ -15,7 +16,6 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
@@ -38,6 +38,7 @@ type InlineSend struct {
}
func (bot TipBot) makeSendKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
inlineSendMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
acceptInlineSendButton := inlineSendMenu.Data(Translate(ctx, "receiveButtonMessage"), "confirm_send_inline")
cancelInlineSendButton := inlineSendMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_send_inline")
acceptInlineSendButton.Data = id
@@ -51,17 +52,17 @@ func (bot TipBot) makeSendKeyboard(ctx context.Context, id string) *tb.ReplyMark
return inlineSendMenu
}
func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) (context.Context, error) {
// inlineSend := NewInlineSend()
// var err error
amount, err := decodeAmountFromCommand(q.Text)
if err != nil {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQuerySendTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
return
return ctx, err
}
if amount < 1 {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
return
return ctx, errors.Create(errors.InvalidAmountError)
}
fromUser := LoadUser(ctx)
fromUserStr := GetUserStr(&q.From)
@@ -69,13 +70,13 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
if err != nil {
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
log.Errorln(errmsg)
return
return ctx, err
}
// check if fromUser has balance
if balance < amount {
log.Errorf("Balance of user %s too low", fromUserStr)
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
return
return ctx, errors.Create(errors.InvalidAmountError)
}
// check whether the 3rd argument is a username
@@ -94,7 +95,7 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
fmt.Sprintf(TranslateUser(ctx, "sendUserHasNoWalletMessage"), to_username),
fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"),
bot.Telegram.Me.Username))
return
return ctx, err
}
memo_argn = 3 // assume that memo starts after the to_username
to_SpecificUser = true
@@ -155,10 +156,12 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
})
if err != nil {
log.Errorln(err)
return ctx, err
}
return ctx, nil
}
func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
to := LoadUser(ctx)
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
@@ -167,14 +170,14 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
// immediatelly set intransaction to block duplicate calls
if err != nil {
// log.Errorf("[acceptInlineSendHandler] %s", err.Error())
return
return ctx, err
}
inlineSend := sn.(*InlineSend)
fromUser := inlineSend.From
if !inlineSend.Active {
log.Errorf("[acceptInlineSendHandler] inline send not active anymore")
return
return ctx, errors.Create(errors.NotActiveError)
}
defer inlineSend.Set(inlineSend, bot.Bunt)
@@ -185,7 +188,7 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
if inlineSend.To_SpecificUser {
if inlineSend.To.Telegram.ID != to.Telegram.ID {
// log.Infof("User %d is not User %d", inlineSend.To.Telegram.ID, to.Telegram.ID)
return
return ctx, errors.Create(errors.UnknownError)
}
} else {
// otherwise, we just set it to the user who has clicked
@@ -194,7 +197,7 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
if fromUser.Telegram.ID == to.Telegram.ID {
bot.trySendMessage(fromUser.Telegram, Translate(ctx, "sendYourselfMessage"))
return
return ctx, errors.Create(errors.UnknownError)
}
toUserStrMd := GetUserStrMd(to.Telegram)
@@ -210,7 +213,7 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
if err != nil {
errmsg := fmt.Errorf("[sendInline] Error: Could not create wallet for %s", toUserStr)
log.Errorln(errmsg)
return
return ctx, err
}
}
// set inactive to avoid double-sends
@@ -225,7 +228,7 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
errMsg := fmt.Sprintf("[sendInline] Transaction failed: %s", err.Error())
log.Errorln(errMsg)
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "inlineSendFailedMessage"), &tb.ReplyMarkup{})
return
return ctx, errors.Create(errors.UnknownError)
}
log.Infof("[💸 sendInline] Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
@@ -246,9 +249,10 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
errmsg := fmt.Errorf("[sendInline] Error: Send message to %s: %s", toUserStr, err)
log.Warnln(errmsg)
}
return ctx, nil
}
func (bot *TipBot) cancelInlineSendHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) cancelInlineSendHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
@@ -256,14 +260,14 @@ func (bot *TipBot) cancelInlineSendHandler(ctx context.Context, c *tb.Callback)
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[cancelInlineSendHandler] %s", err.Error())
return
return ctx, err
}
inlineSend := sn.(*InlineSend)
if c.Sender.ID == inlineSend.From.Telegram.ID {
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
// set the inlineSend inactive
inlineSend.Active = false
runtime.IgnoreError(inlineSend.Set(inlineSend, bot.Bunt))
if c.Sender.ID != inlineSend.From.Telegram.ID {
return ctx, errors.Create(errors.UnknownError)
}
return
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
// set the inlineSend inactive
inlineSend.Active = false
return ctx, inlineSend.Set(inlineSend, bot.Bunt)
}
+7 -2
View File
@@ -2,11 +2,12 @@ package intercept
import (
"context"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type CallbackFuncHandler func(ctx context.Context, message *tb.Callback)
type CallbackFuncHandler func(ctx context.Context, message *tb.Callback) (context.Context, error)
type Func func(ctx context.Context, message interface{}) (context.Context, error)
type handlerCallbackInterceptor struct {
@@ -63,7 +64,11 @@ func HandlerWithCallback(handler CallbackFuncHandler, option ...CallbackIntercep
return
}
defer interceptCallback(ctx, c, hm.onDefer)
hm.handler(ctx, c)
ctx, err = hm.handler(ctx, c)
if err != nil {
log.Traceln(err)
return
}
_, err = interceptCallback(ctx, c, hm.after)
if err != nil {
log.Traceln(err)
+6 -5
View File
@@ -7,10 +7,7 @@ import (
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type MessageInterface interface {
a() func(ctx context.Context, message *tb.Message)
}
type MessageFuncHandler func(ctx context.Context, message *tb.Message)
type MessageFuncHandler func(ctx context.Context, message *tb.Message) (context.Context, error)
type handlerMessageInterceptor struct {
handler MessageFuncHandler
@@ -66,7 +63,11 @@ func HandlerWithMessage(handler MessageFuncHandler, option ...MessageInterceptOp
return
}
defer interceptMessage(ctx, message, hm.onDefer)
hm.handler(ctx, message)
ctx, err = hm.handler(ctx, message)
if err != nil {
log.Traceln(err)
return
}
_, err = interceptMessage(ctx, message, hm.after)
if err != nil {
log.Traceln(err)
+6 -2
View File
@@ -7,7 +7,7 @@ import (
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type QueryFuncHandler func(ctx context.Context, message *tb.Query)
type QueryFuncHandler func(ctx context.Context, message *tb.Query) (context.Context, error)
type handlerQueryInterceptor struct {
handler QueryFuncHandler
@@ -63,7 +63,11 @@ func HandlerWithQuery(handler QueryFuncHandler, option ...QueryInterceptOption)
return
}
defer interceptQuery(ctx, query, hm.onDefer)
hm.handler(ctx, query)
ctx, err = hm.handler(ctx, query)
if err != nil {
log.Traceln(err)
return
}
_, err = interceptQuery(ctx, query, hm.after)
if err != nil {
log.Traceln(err)
+51 -36
View File
@@ -6,6 +6,8 @@ import (
"reflect"
"strconv"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/once"
@@ -26,8 +28,6 @@ const (
QueryInterceptor
)
var invalidTypeError = fmt.Errorf("invalid type")
type Interceptor struct {
Type InterceptorType
Before []intercept.Func
@@ -43,35 +43,7 @@ func (bot TipBot) singletonCallbackInterceptor(ctx context.Context, i interface{
c := i.(*tb.Callback)
return ctx, once.Once(c.Data, strconv.FormatInt(c.Sender.ID, 10))
}
return ctx, invalidTypeError
}
// unlockInterceptor invoked as onDefer interceptor
func (bot TipBot) unlockInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
user := getTelegramUserFromInterface(i)
if user != nil {
mutex.Unlock(strconv.FormatInt(user.ID, 10))
}
return ctx, invalidTypeError
}
func (bot TipBot) idInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
return context.WithValue(ctx, "uid", RandStringRunes(64)), nil
}
func (bot TipBot) answerCallbackInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
switch i.(type) {
case *tb.Callback:
c := i.(*tb.Callback)
ctxcr := ctx.Value("callback_response")
var res []*tb.CallbackResponse
if ctxcr != nil {
res = append(res, &tb.CallbackResponse{CallbackID: c.ID, Text: ctxcr.(string)})
}
var err error
err = bot.Telegram.Respond(c, res...)
return ctx, err
}
return ctx, invalidTypeError
return ctx, errors.Create(errors.InvalidTypeError)
}
// lockInterceptor invoked as first before interceptor
@@ -81,7 +53,41 @@ func (bot TipBot) lockInterceptor(ctx context.Context, i interface{}) (context.C
mutex.Lock(strconv.FormatInt(user.ID, 10))
return ctx, nil
}
return nil, invalidTypeError
return nil, errors.Create(errors.InvalidTypeError)
}
// unlockInterceptor invoked as onDefer interceptor
func (bot TipBot) unlockInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
user := getTelegramUserFromInterface(i)
if user != nil {
mutex.Unlock(strconv.FormatInt(user.ID, 10))
return ctx, nil
}
return ctx, errors.Create(errors.InvalidTypeError)
}
func (bot TipBot) idInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
return context.WithValue(ctx, "uid", RandStringRunes(64)), nil
}
// 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)
ctxcr := ctx.Value("callback_response")
var res []*tb.CallbackResponse
if ctxcr != nil {
res = append(res, &tb.CallbackResponse{CallbackID: c.ID, Text: ctxcr.(string)})
}
// if the context wasn't set, still respond with an empty callback response
if len(res) == 0 {
res = append(res, &tb.CallbackResponse{CallbackID: c.ID, Text: ""})
}
var err error
err = bot.Telegram.Respond(c, res...)
return ctx, err
}
return ctx, errors.Create(errors.InvalidTypeError)
}
// requireUserInterceptor will return an error if user is not found
@@ -92,15 +98,24 @@ func (bot TipBot) requireUserInterceptor(ctx context.Context, i interface{}) (co
u := getTelegramUserFromInterface(i)
if u != nil {
user, err = GetUser(u, bot)
// do not respond to banned users
if bot.UserIsBanned(user) {
ctx = context.WithValue(ctx, "banned", true)
return context.WithValue(ctx, "user", user), errors.Create(errors.InvalidTypeError)
}
if user != nil {
return context.WithValue(ctx, "user", user), err
}
}
return nil, invalidTypeError
return nil, errors.Create(errors.InvalidTypeError)
}
func (bot TipBot) loadUserInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
ctx, _ = bot.requireUserInterceptor(ctx, i)
// if user is banned, also loadUserInterceptor will return an error
if ctx.Value("banned") != nil && ctx.Value("banned").(bool) {
return nil, errors.Create(errors.InvalidTypeError)
}
return ctx, nil
}
@@ -133,7 +148,7 @@ func (bot TipBot) loadReplyToInterceptor(ctx context.Context, i interface{}) (co
}
return ctx, nil
}
return ctx, invalidTypeError
return ctx, errors.Create(errors.InvalidTypeError)
}
func (bot TipBot) localizerInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
@@ -180,7 +195,7 @@ func (bot TipBot) requirePrivateChatInterceptor(ctx context.Context, i interface
}
return ctx, nil
}
return nil, invalidTypeError
return nil, errors.Create(errors.InvalidTypeError)
}
const photoTag = "<Photo>"
@@ -204,7 +219,7 @@ func (bot TipBot) logMessageInterceptor(ctx context.Context, i interface{}) (con
log.Infof("[Callback %s:%d] Data: %s", GetUserStr(m.Sender), m.Sender.ID, m.Data)
return ctx, nil
}
return nil, invalidTypeError
return nil, errors.Create(errors.InvalidTypeError)
}
// LoadUser from context
+20 -11
View File
@@ -7,6 +7,8 @@ import (
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal"
log "github.com/sirupsen/logrus"
@@ -67,25 +69,25 @@ func helpInvoiceUsage(ctx context.Context, errormsg string) string {
}
}
func (bot *TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) invoiceHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
// check and print all commands
bot.anyTextHandler(ctx, m)
user := LoadUser(ctx)
if user.Wallet == nil {
return
return ctx, errors.Create(errors.UserNoWalletError)
}
userStr := GetUserStr(user.Telegram)
if m.Chat.Type != tb.ChatPrivate {
// delete message
bot.tryDeleteMessage(m)
return
return ctx, errors.Create(errors.NoPrivateChatError)
}
// if no amount is in the command, ask for it
amount, err := decodeAmountFromCommand(m.Text)
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
// // no amount was entered, set user state and ask fo""r amount
bot.askForAmount(ctx, "", "CreateInvoiceState", 0, 0, m.Text)
return
_, err = bot.askForAmount(ctx, "", "CreateInvoiceState", 0, 0, m.Text)
return ctx, err
}
// check for memo in command
@@ -100,14 +102,14 @@ func (bot *TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
memo = memo + tag
}
creatingMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
log.Infof("[/invoice] Creating invoice for %s of %d sat.", userStr, amount)
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, "")
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
log.Errorln(errmsg)
return
return ctx, err
}
// create qr code
@@ -116,7 +118,7 @@ func (bot *TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
log.Errorln(errmsg)
return
return ctx, err
}
// deleting messages will delete the main menu.
@@ -125,7 +127,7 @@ func (bot *TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
// send the invoice data to user
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
log.Printf("[/invoice] Incvoice created. User: %s, amount: %d sat.", userStr, amount)
return
return ctx, nil
}
func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User, amount int64, memo string, callback int, callbackData string) (InvoiceEvent, error) {
@@ -174,6 +176,7 @@ type LNURLInvoice struct {
CreatedAt time.Time `json:"created_at"`
Paid bool `json:"paid"`
PaidAt time.Time `json:"paid_at"`
From string `json:"from"`
}
func (lnurlInvoice LNURLInvoice) Key() string {
@@ -187,7 +190,13 @@ func (bot *TipBot) lnurlReceiveEvent(invoiceEvent *InvoiceEvent) {
log.Debugf("[lnurl-p] Received invoice for %s of %d sat.", GetUserStr(invoiceEvent.User.Telegram), tx.Amount)
if err == nil {
if len(tx.Comment) > 0 {
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf(`✉️ %s`, str.MarkdownEscape(tx.Comment)))
if len(tx.From) == 0 {
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(tx.Comment)))
} else {
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("✉️ From `%s`: %s", tx.From, str.MarkdownEscape(tx.Comment)))
}
} else if len(tx.From) > 0 {
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf("From `%s`", str.MarkdownEscape(tx.From)))
}
}
}
+8 -8
View File
@@ -4,7 +4,6 @@ import (
"bytes"
"context"
"fmt"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal"
@@ -14,10 +13,10 @@ import (
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
if internal.Configuration.Lnbits.LnbitsPublicUrl == "" {
bot.trySendMessage(m.Sender, Translate(ctx, "couldNotLinkMessage"))
return
return ctx, fmt.Errorf("invalid configuration")
}
// check and print all commands
bot.anyTextHandler(ctx, m)
@@ -31,8 +30,9 @@ func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
bot.trySendMessage(m.Sender, Translate(ctx, "walletConnectMessage"))
// do not respond to banned users
if strings.HasPrefix(fromUser.Wallet.Adminkey, "banned") || strings.HasPrefix(fromUser.Wallet.Adminkey, "_") {
return
if bot.UserIsBanned(fromUser) {
log.Warnln("[lndhubHandler] user is banned. not responding.")
return ctx, fmt.Errorf("user is banned")
}
lndhubUrl := fmt.Sprintf("lndhub://admin:%s@%slndhub/ext/", fromUser.Wallet.Adminkey, internal.Configuration.Lnbits.LnbitsPublicUrl)
@@ -42,7 +42,7 @@ func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
log.Errorln(errmsg)
return
return ctx, err
}
// send the link to the user
@@ -51,9 +51,9 @@ func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
go func() {
time.Sleep(time.Second * 60)
bot.tryDeleteMessage(linkmsg)
bot.trySendMessage(m.Sender, Translate(ctx, "linkHiddenMessage"))
}()
bot.trySendMessage(m.Sender, Translate(ctx, "linkHiddenMessage"))
// auto delete the message
// NewMessage(linkmsg, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
return ctx, nil
}
+149
View File
@@ -0,0 +1,149 @@
package telegram
import (
"context"
"encoding/json"
"fmt"
"net/url"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/imroc/req"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
lnurl "github.com/fiatjaf/go-lnurl"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
var (
authConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
btnCancelAuth = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_login")
btnAuth = paymentConfirmationMenu.Data("✅ Login", "confirm_login")
)
type LnurlAuthState struct {
*storage.Base
From *lnbits.User `json:"from"`
LNURLAuthParams lnurl.LNURLAuthParams `json:"LNURLAuthParams"`
Comment string `json:"comment"`
LanguageCode string `json:"languagecode"`
Message *tb.Message `json:"message"`
}
// lnurlPayHandler1 is invoked when the first lnurl response was a lnurlpay response
// at this point, the user hans't necessarily entered an amount yet
func (bot *TipBot) lnurlAuthHandler(ctx context.Context, m *tb.Message, authParams *LnurlAuthState) (context.Context, error) {
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
// object that holds all information about the send payment
id := fmt.Sprintf("lnurlauth-%d-%s", m.Sender.ID, RandStringRunes(5))
authParams.Base = storage.New(storage.ID(id))
authParams.From = user
authParams.LanguageCode = ctx.Value("publicLanguageCode").(string)
// // // create inline buttons
btnAuth = paymentConfirmationMenu.Data(Translate(ctx, "loginButtonMessage"), "confirm_login", id)
btnCancelAuth = paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_login", id)
paymentConfirmationMenu.Inline(
paymentConfirmationMenu.Row(
btnAuth,
btnCancelAuth),
)
authParams.Message = bot.trySendMessageEditable(m.Chat,
fmt.Sprintf(Translate(ctx, "confirmLnurlAuthMessager"),
authParams.LNURLAuthParams.CallbackURL.Host,
),
paymentConfirmationMenu,
)
// save to bunt
runtime.IgnoreError(authParams.Set(authParams, bot.Bunt))
return ctx, nil
}
func (bot *TipBot) confirmLnurlAuthHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
tx := &LnurlAuthState{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.Bunt)
// immediatelly set intransaction to block duplicate calls
if err != nil {
log.Errorf("[confirmPayHandler] %s", err.Error())
return ctx, err
}
lnurlAuthState := sn.(*LnurlAuthState)
if !lnurlAuthState.Active {
return ctx, fmt.Errorf("LnurlAuthData not active.")
}
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
// statusMsg := bot.trySendMessageEditable(c.Sender,
// Translate(ctx, "lnurlResolvingUrlMessage"),
// )
bot.editSingleButton(ctx, c.Message, lnurlAuthState.Message.Text, Translate(ctx, "lnurlResolvingUrlMessage"))
// from fiatjaf/go-lnurl
p := lnurlAuthState.LNURLAuthParams
key, sig, err := user.SignKeyAuth(p.Host, p.K1)
if err != nil {
return ctx, err
}
var sentsigres lnurl.LNURLResponse
client, err := bot.GetHttpClient()
if err != nil {
return ctx, err
}
r := req.New()
r.SetClient(client)
res, err := r.Get(p.CallbackURL.String(), url.Values{"sig": {sig}, "key": {key}})
if err != nil {
return ctx, err
}
err = json.Unmarshal(res.Bytes(), &sentsigres)
if err != nil {
return ctx, err
}
if sentsigres.Status == "ERROR" {
bot.tryEditMessage(c.Message, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), sentsigres.Reason))
return ctx, err
}
bot.editSingleButton(ctx, c.Message, lnurlAuthState.Message.Text, Translate(ctx, "lnurlSuccessfulLogin"))
return ctx, lnurlAuthState.Inactivate(lnurlAuthState, bot.Bunt)
}
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
func (bot *TipBot) cancelLnurlAuthHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
tx := &LnurlAuthState{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.Bunt)
// immediatelly set intransaction to block duplicate calls
if err != nil {
log.Errorf("[confirmPayHandler] %s", err.Error())
return ctx, err
}
lnurlAuthState := sn.(*LnurlAuthState)
// onnly the correct user can press
if lnurlAuthState.From.Telegram.ID != c.Sender.ID {
return ctx, errors.Create(errors.UnknownError)
}
// delete and send instead of edit for the keyboard to pop up after sending
bot.tryEditMessage(c.Message, i18n.Translate(lnurlAuthState.LanguageCode, "loginCancelledMessage"), &tb.ReplyMarkup{})
// bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"), &tb.ReplyMarkup{})
return ctx, lnurlAuthState.Inactivate(lnurlAuthState, bot.Bunt)
}
+34 -34
View File
@@ -9,6 +9,7 @@ import (
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
@@ -33,19 +34,16 @@ type LnurlPayState struct {
// lnurlPayHandler1 is invoked when the first lnurl response was a lnurlpay response
// at this point, the user hans't necessarily entered an amount yet
func (bot *TipBot) lnurlPayHandler(ctx context.Context, m *tb.Message, payParams LnurlPayState) {
func (bot *TipBot) lnurlPayHandler(ctx context.Context, m *tb.Message, payParams *LnurlPayState) {
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
// object that holds all information about the send payment
id := fmt.Sprintf("lnurlp-%d-%s", m.Sender.ID, RandStringRunes(5))
lnurlPayState := &LnurlPayState{
Base: storage.New(storage.ID(id)),
From: user,
LNURLPayParams: payParams.LNURLPayParams,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
payParams.Base = storage.New(storage.ID(id))
payParams.From = user
payParams.LanguageCode = ctx.Value("publicLanguageCode").(string)
// first we check whether an amount is present in the command
amount, amount_err := decodeAmountFromCommand(m.Text)
@@ -60,39 +58,42 @@ func (bot *TipBot) lnurlPayHandler(ctx context.Context, m *tb.Message, payParams
// check if memo is present in command
memo := GetMemoFromCommand(m.Text, memoStartsAt)
// shorten memo to allowed length
if len(memo) > int(lnurlPayState.LNURLPayParams.CommentAllowed) {
memo = memo[:lnurlPayState.LNURLPayParams.CommentAllowed]
if len(memo) > int(payParams.LNURLPayParams.CommentAllowed) {
memo = memo[:payParams.LNURLPayParams.CommentAllowed]
}
if len(memo) > 0 {
lnurlPayState.Comment = memo
payParams.Comment = memo
}
// amount is already present in the command, i.e., /lnurl <amount> <LNURL>
// amount not in allowed range from LNURL
if amount_err == nil &&
(int64(amount) > (lnurlPayState.LNURLPayParams.MaxSendable/1000) || int64(amount) < (lnurlPayState.LNURLPayParams.MinSendable/1000)) &&
(lnurlPayState.LNURLPayParams.MaxSendable != 0 && lnurlPayState.LNURLPayParams.MinSendable != 0) { // only if max and min are set
(int64(amount) > (payParams.LNURLPayParams.MaxSendable/1000) || int64(amount) < (payParams.LNURLPayParams.MinSendable/1000)) &&
(payParams.LNURLPayParams.MaxSendable != 0 && payParams.LNURLPayParams.MinSendable != 0) { // only if max and min are set
err := fmt.Errorf("amount not in range")
log.Warnf("[lnurlPayHandler] Error: %s", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), lnurlPayState.LNURLPayParams.MinSendable/1000, lnurlPayState.LNURLPayParams.MaxSendable/1000))
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), payParams.LNURLPayParams.MinSendable/1000, payParams.LNURLPayParams.MaxSendable/1000))
ResetUserState(user, bot)
return
}
// set also amount in the state of the user
lnurlPayState.Amount = amount * 1000 // save as mSat
payParams.Amount = amount * 1000 // save as mSat
// add result to persistent struct
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
runtime.IgnoreError(payParams.Set(payParams, bot.Bunt))
// now we actualy check whether the amount was in the command and if not, ask for it
if amount_err != nil || amount < 1 {
if payParams.LNURLPayParams.MinSendable == payParams.LNURLPayParams.MaxSendable {
amount = payParams.LNURLPayParams.MaxSendable / 1000
payParams.Amount = amount * 1000 // save as mSat
} else if amount_err != nil || amount < 1 {
// // no amount was entered, set user state and ask for amount
bot.askForAmount(ctx, id, "LnurlPayState", lnurlPayState.LNURLPayParams.MinSendable, lnurlPayState.LNURLPayParams.MaxSendable, m.Text)
bot.askForAmount(ctx, id, "LnurlPayState", payParams.LNURLPayParams.MinSendable, payParams.LNURLPayParams.MaxSendable, m.Text)
return
}
// We need to save the pay state in the user state so we can load the payment in the next handler
paramsJson, err := json.Marshal(lnurlPayState)
paramsJson, err := json.Marshal(payParams)
if err != nil {
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
// bot.trySendMessage(m.Sender, err.Error())
@@ -105,10 +106,10 @@ func (bot *TipBot) lnurlPayHandler(ctx context.Context, m *tb.Message, payParams
}
// lnurlPayHandlerSend is invoked when the user has delivered an amount and is ready to pay
func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) (context.Context, error) {
user := LoadUser(ctx)
if user.Wallet == nil {
return
return ctx, errors.Create(errors.UserNoWalletError)
}
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
@@ -116,7 +117,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
if user.StateKey != lnbits.UserHasEnteredAmount {
log.Errorln("[lnurlPayHandlerSend] state keys don't match")
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
return ctx, fmt.Errorf("wrong state key")
}
// read the enter amount state from user.StateData
@@ -125,9 +126,8 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
return ctx, err
}
// use the enter amount state of the user to load the LNURL payment state
tx := &LnurlPayState{Base: storage.New(storage.ID(enterAmountData.ID))}
mutex.LockWithContext(ctx, tx.ID)
@@ -136,7 +136,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
return ctx, err
}
lnurlPayState := fn.(*LnurlPayState)
@@ -146,13 +146,13 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
return ctx, err
}
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
return ctx, err
}
qs := callbackUrl.Query()
// add amount to query string
@@ -168,13 +168,13 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
return ctx, err
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
return ctx, err
}
var response2 lnurl.LNURLPayValues
@@ -186,7 +186,7 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
}
log.Errorf("[lnurlPayHandler] Error in LNURLPayValues: %s", error_reason)
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
return
return ctx, fmt.Errorf("Error in LNURLPayValues: %s", error_reason)
}
lnurlPayState.LNURLPayValues = response2
@@ -194,13 +194,13 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
bot.Telegram.Delete(statusMsg)
m.Text = fmt.Sprintf("/pay %s", response2.PR)
bot.payHandler(ctx, m)
return bot.payHandler(ctx, m)
}
func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, address string, amount int64) error {
func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, address string, amount int64) (context.Context, error) {
split := strings.Split(address, "@")
if len(split) != 2 {
return fmt.Errorf("lightning address format wrong")
return ctx, fmt.Errorf("lightning address format wrong")
}
host := strings.ToLower(split[1])
name := strings.ToLower(split[0])
@@ -212,7 +212,7 @@ func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, ad
lnurl, err := lnurl.LNURLEncode(callback)
if err != nil {
return err
return ctx, err
}
if amount > 0 {
@@ -233,5 +233,5 @@ func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, ad
m.Text = fmt.Sprintf("/lnurl %s", lnurl)
}
bot.lnurlHandler(ctx, m)
return nil
return ctx, nil
}
+44 -44
View File
@@ -7,6 +7,8 @@ import (
"io/ioutil"
"net/url"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
@@ -41,6 +43,7 @@ type LnurlWithdrawState struct {
Message string `json:"message"`
}
// 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(
m,
@@ -55,19 +58,17 @@ func (bot *TipBot) editSingleButton(ctx context.Context, m *tb.Message, message
// lnurlWithdrawHandler is invoked when the first lnurl response was a lnurl-withdraw response
// at this point, the user hans't necessarily entered an amount yet
func (bot *TipBot) lnurlWithdrawHandler(ctx context.Context, m *tb.Message, withdrawParams LnurlWithdrawState) {
func (bot *TipBot) lnurlWithdrawHandler(ctx context.Context, m *tb.Message, withdrawParams *LnurlWithdrawState) {
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
// object that holds all information about the send payment
id := fmt.Sprintf("lnurlw-%d-%s", m.Sender.ID, RandStringRunes(5))
LnurlWithdrawState := LnurlWithdrawState{
Base: storage.New(storage.ID(id)),
From: user,
LNURLWithdrawResponse: withdrawParams.LNURLWithdrawResponse,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
withdrawParams.Base = storage.New(storage.ID(id))
withdrawParams.From = user
withdrawParams.LanguageCode = ctx.Value("publicLanguageCode").(string)
// first we check whether an amount is present in the command
amount, amount_err := decodeAmountFromCommand(m.Text)
@@ -75,36 +76,36 @@ func (bot *TipBot) lnurlWithdrawHandler(ctx context.Context, m *tb.Message, with
// amount is already present in the command, i.e., /lnurl <amount> <LNURL>
// amount not in allowed range from LNURL
if amount_err == nil &&
(int64(amount) > (LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable/1000) || int64(amount) < (LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable/1000)) &&
(LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable != 0 && LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable != 0) { // only if max and min are set
(int64(amount) > (withdrawParams.LNURLWithdrawResponse.MaxWithdrawable/1000) || int64(amount) < (withdrawParams.LNURLWithdrawResponse.MinWithdrawable/1000)) &&
(withdrawParams.LNURLWithdrawResponse.MaxWithdrawable != 0 && withdrawParams.LNURLWithdrawResponse.MinWithdrawable != 0) { // only if max and min are set
err := fmt.Errorf("amount not in range")
log.Warnf("[lnurlWithdrawHandler] Error: %s", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable/1000, LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable/1000))
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), withdrawParams.LNURLWithdrawResponse.MinWithdrawable/1000, withdrawParams.LNURLWithdrawResponse.MaxWithdrawable/1000))
ResetUserState(user, bot)
return
}
// if no amount is entered, and if only one amount is possible, we use it
if amount_err != nil && LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable == LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable {
amount = int64(LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable / 1000)
if amount_err != nil && withdrawParams.LNURLWithdrawResponse.MaxWithdrawable == withdrawParams.LNURLWithdrawResponse.MinWithdrawable {
amount = int64(withdrawParams.LNURLWithdrawResponse.MaxWithdrawable / 1000)
amount_err = nil
}
// set also amount in the state of the user
LnurlWithdrawState.Amount = amount * 1000 // save as mSat
withdrawParams.Amount = amount * 1000 // save as mSat
// add result to persistent struct
runtime.IgnoreError(LnurlWithdrawState.Set(LnurlWithdrawState, bot.Bunt))
runtime.IgnoreError(withdrawParams.Set(withdrawParams, bot.Bunt))
// now we actualy check whether the amount was in the command and if not, ask for it
if amount_err != nil || amount < 1 {
// // no amount was entered, set user state and ask for amount
bot.askForAmount(ctx, id, "LnurlWithdrawState", LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable, LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable, m.Text)
bot.askForAmount(ctx, id, "LnurlWithdrawState", withdrawParams.LNURLWithdrawResponse.MinWithdrawable, withdrawParams.LNURLWithdrawResponse.MaxWithdrawable, m.Text)
return
}
// We need to save the pay state in the user state so we can load the payment in the next handler
paramsJson, err := json.Marshal(LnurlWithdrawState)
paramsJson, err := json.Marshal(withdrawParams)
if err != nil {
log.Errorf("[lnurlWithdrawHandler] Error: %s", err.Error())
// bot.trySendMessage(m.Sender, err.Error())
@@ -117,18 +118,18 @@ func (bot *TipBot) lnurlWithdrawHandler(ctx context.Context, m *tb.Message, with
}
// lnurlWithdrawHandlerWithdraw is invoked when the user has delivered an amount and is ready to pay
func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Message) {
func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Message) (context.Context, error) {
user := LoadUser(ctx)
if user.Wallet == nil {
return
return ctx, errors.Create(errors.UserNoWalletError)
}
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlPreparingWithdraw"))
statusMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "lnurlPreparingWithdraw"))
// assert that user has entered an amount
if user.StateKey != lnbits.UserHasEnteredAmount {
log.Errorln("[lnurlWithdrawHandlerWithdraw] state keys don't match")
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
return ctx, fmt.Errorf("wrong state key")
}
// read the enter amount state from user.StateData
@@ -137,7 +138,7 @@ func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Messa
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
return ctx, err
}
// use the enter amount state of the user to load the LNURL payment state
@@ -148,7 +149,7 @@ func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Messa
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
return ctx, err
}
var lnurlWithdrawState *LnurlWithdrawState
switch fn.(type) {
@@ -157,7 +158,7 @@ func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Messa
default:
log.Errorf("[lnurlWithdrawHandlerWithdraw] invalid type")
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return
return ctx, fmt.Errorf("invalid type")
}
confirmText := fmt.Sprintf(Translate(ctx, "confirmLnurlWithdrawMessage"), lnurlWithdrawState.Amount/1000)
@@ -167,10 +168,8 @@ func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Messa
lnurlWithdrawState.Message = confirmText
// create inline buttons
withdrawButton := paymentConfirmationMenu.Data(Translate(ctx, "withdrawButtonMessage"), "confirm_withdraw")
btnCancelWithdraw := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_withdraw")
withdrawButton.Data = lnurlWithdrawState.ID
btnCancelWithdraw.Data = lnurlWithdrawState.ID
withdrawButton := paymentConfirmationMenu.Data(Translate(ctx, "withdrawButtonMessage"), "confirm_withdraw", lnurlWithdrawState.ID)
btnCancelWithdraw := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_withdraw", lnurlWithdrawState.ID)
withdrawConfirmationMenu.Inline(
withdrawConfirmationMenu.Row(
@@ -183,17 +182,18 @@ func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Messa
// // add response to persistent struct
// lnurlWithdrawState.LNURResponse = response2
runtime.IgnoreError(lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt))
return ctx, nil
}
// confirmPayHandler when user clicked pay on payment confirmation
func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[confirmWithdrawHandler] Error: %s", err.Error())
return
return ctx, err
}
var lnurlWithdrawState *LnurlWithdrawState
@@ -202,24 +202,24 @@ func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) {
lnurlWithdrawState = fn.(*LnurlWithdrawState)
default:
log.Errorf("[confirmWithdrawHandler] invalid type")
return
return ctx, errors.Create(errors.InvalidTypeError)
}
// onnly the correct user can press
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
return
return ctx, errors.Create(errors.UnknownError)
}
if !lnurlWithdrawState.Active {
log.Errorf("[confirmPayHandler] send not active anymore")
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
bot.tryDeleteMessage(c.Message)
return
return ctx, errors.Create(errors.NotActiveError)
}
defer lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt)
user := LoadUser(ctx)
if user.Wallet == nil {
bot.tryDeleteMessage(c.Message)
return
return ctx, errors.Create(errors.UserNoWalletError)
}
// reset state immediately
@@ -233,7 +233,7 @@ func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
return
return ctx, err
}
// generate an invoice and add the pr to the request
@@ -249,7 +249,7 @@ func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) {
errmsg := fmt.Sprintf("[lnurlWithdrawHandlerWithdraw] Could not create an invoice: %s", err.Error())
log.Errorln(errmsg)
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
return
return ctx, err
}
lnurlWithdrawState.Invoice = invoice
@@ -265,21 +265,21 @@ func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
return
return ctx, err
}
res, err := client.Get(callbackUrl.String())
if err != nil || res.StatusCode >= 300 {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Failed.")
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
return
return ctx, errors.New(errors.UnknownError, err)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
return
return ctx, err
}
// parse the response
@@ -293,17 +293,17 @@ func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) {
log.Errorf("[lnurlWithdrawHandlerWithdraw] LNURLWithdraw failed.")
// update button text
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawFailed"))
return
return ctx, errors.New(errors.UnknownError, fmt.Errorf("LNURLWithdraw failed"))
}
// add response to persistent struct
lnurlWithdrawState.LNURResponse = response2
runtime.IgnoreError(lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt))
return ctx, lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt)
}
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
func (bot *TipBot) cancelWithdrawHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) cancelWithdrawHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
// reset state immediately
user := LoadUser(ctx)
ResetUserState(user, bot)
@@ -313,7 +313,7 @@ func (bot *TipBot) cancelWithdrawHandler(ctx context.Context, c *tb.Callback) {
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[cancelWithdrawHandler] Error: %s", err.Error())
return
return ctx, err
}
var lnurlWithdrawState *LnurlWithdrawState
switch fn.(type) {
@@ -324,8 +324,8 @@ func (bot *TipBot) cancelWithdrawHandler(ctx context.Context, c *tb.Callback) {
}
// onnly the correct user can press
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
return
return ctx, errors.Create(errors.UnknownError)
}
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawCancelled"), &tb.ReplyMarkup{})
lnurlWithdrawState.Inactivate(lnurlWithdrawState, bot.Bunt)
return ctx, lnurlWithdrawState.Inactivate(lnurlWithdrawState, bot.Bunt)
}
+47 -30
View File
@@ -3,13 +3,14 @@ package telegram
import (
"bytes"
"context"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/tidwall/gjson"
@@ -36,26 +37,25 @@ func (bot TipBot) cancelLnUrlHandler(c *tb.Callback) {
}
// lnurlHandler is invoked on /lnurl command
func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
// commands:
// /lnurl
// /lnurl <LNURL>
// or /lnurl <amount> <LNURL>
if m.Chat.Type != tb.ChatPrivate {
return
return ctx, errors.Create(errors.NoPrivateChatError)
}
log.Infof("[lnurlHandler] %s", m.Text)
user := LoadUser(ctx)
if user.Wallet == nil {
return
return ctx, errors.Create(errors.UserNoWalletError)
}
// if only /lnurl is entered, show the lnurl of the user
if m.Text == "/lnurl" {
bot.lnurlReceiveHandler(ctx, m)
return
return bot.lnurlReceiveHandler(ctx, m)
}
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlResolvingUrlMessage"))
statusMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "lnurlResolvingUrlMessage"))
var lnurlSplit string
split := strings.Split(m.Text, " ")
@@ -69,39 +69,61 @@ func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) {
} else {
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "Could not parse command."))
log.Warnln("[/lnurl] Could not parse command.")
return
return ctx, errors.Create(errors.InvalidSyntaxError)
}
// get rid of the URI prefix
lnurlSplit = strings.TrimPrefix(lnurlSplit, "lightning:")
log.Debugf("[lnurlHandler] lnurlSplit: %s", lnurlSplit)
// HandleLNURL by fiatjaf/go-lnurl
_, params, err := bot.HandleLNURL(lnurlSplit)
if err != nil {
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "LNURL error."))
// bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
log.Warnf("[HandleLNURL] Error: %s", err.Error())
return
return ctx, err
}
switch params.(type) {
case lnurl.LNURLAuthParams:
authParams := &LnurlAuthState{LNURLAuthParams: params.(lnurl.LNURLAuthParams)}
log.Infof("[LNURL-auth] %s", authParams.LNURLAuthParams.Callback)
bot.tryDeleteMessage(statusMsg)
return bot.lnurlAuthHandler(ctx, m, authParams)
case lnurl.LNURLPayParams:
payParams := &LnurlPayState{LNURLPayParams: params.(lnurl.LNURLPayParams)}
log.Infof("[LNURL-p] %s", payParams.LNURLPayParams.Callback)
bot.tryDeleteMessage(statusMsg)
bot.lnurlPayHandler(ctx, m, *payParams)
return
// display the metadata image from the first LNURL-p response
if len(payParams.LNURLPayParams.Metadata.Image.Bytes) > 0 {
bot.trySendMessage(m.Sender, &tb.Photo{
File: tb.File{FileReader: bytes.NewReader(payParams.LNURLPayParams.Metadata.Image.Bytes)},
Caption: fmt.Sprintf("%s", payParams.LNURLPayParams.Metadata.Description)})
} else if len(payParams.LNURLPayParams.Metadata.Description) > 0 {
// display the metadata text from the first LNURL-p response
// if there was no photo in the last step
bot.trySendMessage(m.Sender, fmt.Sprintf("`%s`", payParams.LNURLPayParams.Metadata.Description))
}
// ask whether to make payment
bot.lnurlPayHandler(ctx, m, payParams)
case lnurl.LNURLWithdrawResponse:
withdrawParams := LnurlWithdrawState{LNURLWithdrawResponse: params.(lnurl.LNURLWithdrawResponse)}
withdrawParams := &LnurlWithdrawState{LNURLWithdrawResponse: params.(lnurl.LNURLWithdrawResponse)}
log.Infof("[LNURL-w] %s", withdrawParams.LNURLWithdrawResponse.Callback)
bot.tryDeleteMessage(statusMsg)
bot.lnurlWithdrawHandler(ctx, m, withdrawParams)
default:
if err == nil {
err = errors.New("Invalid LNURL type.")
err = fmt.Errorf("invalid LNURL type")
}
log.Warnln(err)
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
// bot.trySendMessage(m.Sender, err.Error())
return
return ctx, err
}
return ctx, nil
}
func (bot *TipBot) UserGetLightningAddress(user *lnbits.User) (string, error) {
@@ -114,18 +136,11 @@ func (bot *TipBot) UserGetLightningAddress(user *lnbits.User) (string, error) {
}
func (bot *TipBot) UserGetAnonLightningAddress(user *lnbits.User) (string, error) {
return fmt.Sprintf("%s@%s", fmt.Sprint(user.AnonID), strings.ToLower(internal.Configuration.Bot.LNURLHostUrl.Hostname())), nil
return fmt.Sprintf("%s@%s", fmt.Sprint(user.AnonIDSha256), strings.ToLower(internal.Configuration.Bot.LNURLHostUrl.Hostname())), nil
}
func UserGetLNURL(user *lnbits.User) (string, error) {
// before: we used the username for the LNURL
// name := strings.ToLower(strings.ToLower(user.Telegram.Username))
// if len(name) == 0 {
// name = fmt.Sprint(user.AnonID)
// // return "", fmt.Errorf("user has no username.")
// }
// now: use only the anon ID as LNURL
name := fmt.Sprint(user.AnonID)
name := fmt.Sprint(user.UUID)
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, name)
log.Debugf("[lnurlReceiveHandler] %s's LNURL: %s", GetUserStr(user.Telegram), callback)
@@ -137,25 +152,27 @@ func UserGetLNURL(user *lnbits.User) (string, error) {
}
// lnurlReceiveHandler outputs the LNURL of the user
func (bot TipBot) lnurlReceiveHandler(ctx context.Context, m *tb.Message) {
func (bot TipBot) lnurlReceiveHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
fromUser := LoadUser(ctx)
lnurlEncode, err := UserGetLNURL(fromUser)
if err != nil {
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to get LNURL: %s", err.Error())
log.Errorln(errmsg)
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlNoUsernameMessage"))
return ctx, err
}
// create qr code
qr, err := qrcode.Encode(lnurlEncode, qrcode.Medium, 256)
if err != nil {
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to create QR code for LNURL: %s", err.Error())
log.Errorln(errmsg)
return
return ctx, err
}
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlReceiveInfoText"))
// send the lnurl data to user
// send the lnurl QR code
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lnurlEncode)})
return ctx, nil
}
// fiatjaf/go-lnurl 1.8.4 with proxy
@@ -188,7 +205,7 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
lnurl_str, ok := lnurl.FindLNURLInText(rawlnurl)
if !ok {
return "", nil,
errors.New("invalid bech32-encoded lnurl: " + rawlnurl)
fmt.Errorf("invalid bech32-encoded lnurl: " + rawlnurl)
}
rawurl, err = lnurl.LNURLDecode(lnurl_str)
if err != nil {
@@ -228,7 +245,7 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
return rawurl, nil, err
}
if resp.StatusCode >= 300 {
return rawurl, nil, errors.New("HTTP error: " + resp.Status)
return rawurl, nil, fmt.Errorf("HTTP error: " + resp.Status)
}
b, err := ioutil.ReadAll(resp.Body)
@@ -256,6 +273,6 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
// value, err := lnurl.HandleChannel(b)
// return rawurl, value, err
default:
return rawurl, nil, errors.New("Unkown LNURL response.")
return rawurl, nil, fmt.Errorf("Unkown LNURL response.")
}
}
+31 -26
View File
@@ -5,6 +5,8 @@ import (
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
@@ -46,17 +48,17 @@ type PayData struct {
}
// payHandler invoked on "/pay lnbc..." command
func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
// check and print all commands
bot.anyTextHandler(ctx, m)
user := LoadUser(ctx)
if user.Wallet == nil {
return
return ctx, errors.Create(errors.UserNoWalletError)
}
if len(strings.Split(m.Text, " ")) < 2 {
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, ""))
return
return ctx, errors.Create(errors.InvalidSyntaxError)
}
userStr := GetUserStr(m.Sender)
paymentRequest, err := getArgumentFromCommand(m.Text, 1)
@@ -65,7 +67,7 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
errmsg := fmt.Sprintf("[/pay] Error: Could not getArgumentFromCommand: %s", err.Error())
log.Errorln(errmsg)
return
return ctx, errors.New(errors.InvalidSyntaxError, err)
}
paymentRequest = strings.ToLower(paymentRequest)
// get rid of the URI prefix
@@ -77,7 +79,7 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err.Error())
log.Errorln(errmsg)
return
return ctx, errors.New(errors.InvalidSyntaxError, err)
}
amount := int64(bolt11.MSatoshi / 1000)
@@ -85,7 +87,7 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
bot.trySendMessage(m.Sender, Translate(ctx, "invoiceNoAmountMessage"))
errmsg := fmt.Sprint("[/pay] Error: invoice without amount")
log.Warnln(errmsg)
return
return ctx, errors.Create(errors.InvalidAmountError)
}
// check user balance first
@@ -95,13 +97,13 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err.Error())
log.Errorln(errmsg)
bot.trySendMessage(m.Sender, Translate(ctx, "errorTryLaterMessage"))
return
return ctx, errors.New(errors.GetBalanceError, err)
}
if amount > balance {
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "insufficientFundsMessage"), balance, amount))
return
return ctx, errors.Create(errors.InvalidSyntaxError)
}
// send warning that the invoice might fail due to missing fee reserve
if float64(amount) > float64(balance)*0.99 {
@@ -119,17 +121,15 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
id := fmt.Sprintf("pay-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
// // // create inline buttons
payButton := paymentConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "confirm_pay")
cancelButton := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_pay")
payButton.Data = id
cancelButton.Data = id
payButton := paymentConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "confirm_pay", id)
cancelButton := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_pay", id)
paymentConfirmationMenu.Inline(
paymentConfirmationMenu.Row(
payButton,
cancelButton),
)
payMessage := bot.trySendMessage(m.Chat, confirmText, paymentConfirmationMenu)
payMessage := bot.trySendMessageEditable(m.Chat, confirmText, paymentConfirmationMenu)
payData := &PayData{
Base: storage.New(storage.ID(id)),
From: user,
@@ -144,10 +144,11 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
runtime.IgnoreError(payData.Set(payData, bot.Bunt))
SetUserState(user, bot, lnbits.UserStateConfirmPayment, paymentRequest)
return ctx, nil
}
// confirmPayHandler when user clicked pay on payment confirmation
func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
tx := &PayData{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
@@ -155,19 +156,19 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
// immediatelly set intransaction to block duplicate calls
if err != nil {
log.Errorf("[confirmPayHandler] %s", err.Error())
return
return ctx, err
}
payData := sn.(*PayData)
// onnly the correct user can press
if payData.From.Telegram.ID != c.Sender.ID {
return
return ctx, errors.Create(errors.UnknownError)
}
if !payData.Active {
log.Errorf("[confirmPayHandler] send not active anymore")
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
bot.tryDeleteMessage(c.Message)
return
return ctx, errors.Create(errors.NotActiveError)
}
defer payData.Set(payData, bot.Bunt)
@@ -177,7 +178,7 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
user := LoadUser(ctx)
if user.Wallet == nil {
bot.tryDeleteMessage(c.Message)
return
return ctx, errors.Create(errors.UserNoWalletError)
}
invoiceString := payData.Invoice
@@ -211,7 +212,7 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
// }
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), str.MarkdownEscape(err.Error())), &tb.ReplyMarkup{})
log.Errorln(errmsg)
return
return ctx, err
}
payData.Hash = invoice.PaymentHash
@@ -224,7 +225,7 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
if c.Message.Private() {
// if the command was invoked in private chat
// the edit below was cool, but we need to get rid of the replymarkup inline keyboard thingy for the main menu button update to work (for the new balance)
// the edit below was cool, but we need to pop up the keyboard again
// bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
bot.tryDeleteMessage(c.Message)
bot.trySendMessage(c.Sender, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
@@ -234,11 +235,11 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePublicPaidMessage"), userStr), &tb.ReplyMarkup{})
}
log.Infof("[⚡️ pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
return
return ctx, nil
}
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
func (bot *TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
// reset state immediately
user := LoadUser(ctx)
ResetUserState(user, bot)
@@ -249,13 +250,17 @@ func (bot *TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) {
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[cancelPaymentHandler] %s", err.Error())
return
return ctx, err
}
payData := sn.(*PayData)
// onnly the correct user can press
if payData.From.Telegram.ID != c.Sender.ID {
return
return ctx, errors.Create(errors.UnknownError)
}
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"), &tb.ReplyMarkup{})
payData.Inactivate(payData, bot.Bunt)
// delete and send instead of edit for the keyboard to pop up after sending
bot.tryDeleteMessage(c.Message)
bot.trySendMessage(c.Message.Chat, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"))
// bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"), &tb.ReplyMarkup{})
return ctx, payData.Inactivate(payData, bot.Bunt)
}
+87 -12
View File
@@ -1,15 +1,21 @@
package telegram
import (
"bytes"
"context"
"encoding/json"
"fmt"
"image"
"image/jpeg"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
"github.com/makiuchi-d/gozxing"
"github.com/makiuchi-d/gozxing/qrcode"
"github.com/nfnt/resize"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
@@ -34,48 +40,117 @@ func TryRecognizeQrCode(img image.Image) (*gozxing.Result, error) {
}
// photoHandler is the handler function for every photo from a private chat that the bot receives
func (bot *TipBot) photoHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) photoHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
if m.Chat.Type != tb.ChatPrivate {
return
return ctx, errors.Create(errors.NoPrivateChatError)
}
if m.Photo == nil {
return
return ctx, errors.Create(errors.NoPhotoError)
}
user := LoadUser(ctx)
if c := stateCallbackMessage[user.StateKey]; c != nil {
c(ctx, m)
ctx, err := c(ctx, m)
ResetUserState(user, bot)
return
return ctx, err
}
// get file reader closer from Telegram api
reader, err := bot.Telegram.GetFile(m.Photo.MediaFile())
if err != nil {
log.Errorf("[photoHandler] getfile error: %v\n", err.Error())
return
return ctx, err
}
// decode to jpeg image
img, err := jpeg.Decode(reader)
if err != nil {
log.Errorf("[photoHandler] image.Decode error: %v\n", err.Error())
return
return ctx, err
}
data, err := TryRecognizeQrCode(img)
if err != nil {
log.Errorf("[photoHandler] tryRecognizeQrCodes error: %v\n", err.Error())
bot.trySendMessage(m.Sender, Translate(ctx, "photoQrNotRecognizedMessage"))
return
return ctx, err
}
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "photoQrRecognizedMessage"), data.String()))
// invoke payment handler
if lightning.IsInvoice(data.String()) {
m.Text = fmt.Sprintf("/pay %s", data.String())
bot.payHandler(ctx, m)
return
return bot.payHandler(ctx, m)
} else if lightning.IsLnurl(data.String()) {
m.Text = fmt.Sprintf("/lnurl %s", data.String())
bot.lnurlHandler(ctx, m)
return
return bot.lnurlHandler(ctx, m)
}
return ctx, nil
}
// DownloadProfilePicture downloads a profile picture from Telegram.
// This is a public function because it is used in another package (lnurl)
func DownloadProfilePicture(telegram *tb.Bot, user *tb.User) ([]byte, error) {
photo, err := ProfilePhotosOf(telegram, user)
if err != nil {
log.Errorf("[DownloadProfilePicture] %v", err)
return nil, err
}
if len(photo) == 0 {
log.Error("[DownloadProfilePicture] No profile picture found")
return nil, err
}
buf := new(bytes.Buffer)
reader, err := telegram.GetFile(&photo[0].File)
if err != nil {
log.Errorf("[DownloadProfilePicture] %v", err)
return nil, err
}
img, err := jpeg.Decode(reader)
if err != nil {
log.Errorf("[DownloadProfilePicture] %v", err)
return nil, err
}
// resize image
img = resize.Thumbnail(160, 160, img, resize.Lanczos3)
err = jpeg.Encode(buf, img, nil)
return buf.Bytes(), nil
}
var BotProfilePicture []byte
// downloadMyProfilePicture downloads the profile picture of the bot
// and saves it in `BotProfilePicture`
func (bot *TipBot) downloadMyProfilePicture() error {
picture, err := DownloadProfilePicture(bot.Telegram, bot.Telegram.Me)
if err != nil {
log.Errorf("[downloadMyProfilePicture] %v", err)
return err
}
BotProfilePicture = picture
return nil
}
// ProfilePhotosOf returns list of profile pictures for a user.
func ProfilePhotosOf(bot *tb.Bot, user *tb.User) ([]tb.Photo, error) {
params := map[string]interface {
}{
"user_id": user.Recipient(),
"limit": 1,
}
data, err := bot.Raw("getUserProfilePhotos", params)
if err != nil {
return nil, err
}
var resp struct {
Result struct {
Count int `json:"total_count"`
Photos []tb.Photo `json:"photos"`
}
}
if err := json.Unmarshal(data, &resp); err != nil {
return nil, err
}
return resp.Result.Photos, nil
}
+75 -30
View File
@@ -6,6 +6,8 @@ import (
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
@@ -53,11 +55,11 @@ type SendData struct {
}
// sendHandler invoked on "/send 123 @user" command
func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
bot.anyTextHandler(ctx, m)
user := LoadUser(ctx)
if user.Wallet == nil {
return
return ctx, errors.Create(errors.UserNoWalletError)
}
// reset state immediately
@@ -67,8 +69,8 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
// If the send is a reply, then trigger /tip handler
if m.IsReply() && m.Chat.Type != tb.ChatPrivate {
bot.tipHandler(ctx, m)
return
return bot.tipHandler(ctx, m)
}
// if ok, errstr := bot.SendCheckSyntax(ctx, m); !ok {
@@ -92,27 +94,27 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
if err == nil {
if lightning.IsLightningAddress(arg) {
// lightning address, send to that address
err = bot.sendToLightningAddress(ctx, m, arg, amount)
ctx, err = bot.sendToLightningAddress(ctx, m, arg, amount)
if err != nil {
log.Errorln(err.Error())
return
return ctx, err
}
return
return ctx, err
}
}
// is a user given?
arg, err = getArgumentFromCommand(m.Text, 1)
if err != nil && m.Chat.Type == tb.ChatPrivate {
bot.askForUser(ctx, "", "CreateSendState", m.Text)
return
_, err = bot.askForUser(ctx, "", "CreateSendState", m.Text)
return ctx, err
}
// is an amount given?
amount, err = decodeAmountFromCommand(m.Text)
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
bot.askForAmount(ctx, "", "CreateSendState", 0, 0, m.Text)
return
_, err = bot.askForAmount(ctx, "", "CreateSendState", 0, 0, m.Text)
return ctx, err
}
// ASSUME INTERNAL SEND TO TELEGRAM USER
@@ -122,7 +124,7 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
// immediately delete if the amount is bullshit
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, helpSendUsage(ctx, Translate(ctx, "sendValidAmountMessage")))
return
return ctx, err
}
// SEND COMMAND IS VALID
@@ -140,7 +142,7 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
toUserStrWithoutAt, err = getArgumentFromCommand(m.Text, 2)
if err != nil {
log.Errorln(err.Error())
return
return ctx, err
}
toUserStrWithoutAt = strings.TrimPrefix(toUserStrWithoutAt, "@")
toUserStrMention = "@" + toUserStrWithoutAt
@@ -148,7 +150,7 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
err = bot.parseCmdDonHandler(ctx, m)
if err == nil {
return
return ctx, errors.Create(errors.InvalidSyntaxError)
}
toUserDb, err := GetUserByTelegramUsername(toUserStrWithoutAt, *bot)
@@ -159,12 +161,12 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
toUserStrMention = toUserStrMention[:100]
}
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), str.MarkdownEscape(toUserStrMention)))
return
return ctx, err
}
if user.ID == toUserDb.ID {
bot.trySendMessage(m.Sender, Translate(ctx, "sendYourselfMessage"))
return
return ctx, errors.Create(errors.SelfPaymentError)
}
// entire text of the inline object
@@ -192,7 +194,7 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
NewMessage(m, WithDuration(0, bot))
log.Printf("[/send] Error: %s\n", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprint(Translate(ctx, "errorTryLaterMessage")))
return
return ctx, err
}
// save the send data to the Database
// log.Debug(sendData)
@@ -212,27 +214,68 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
} else {
bot.tryReplyMessage(m, confirmText, sendConfirmationMenu)
}
return ctx, nil
}
// keyboardSendHandler will be called when the user presses the Send button on the keyboard
// it will pop up a new keyboard with the last interacted contacts to send funds to
// then, the flow is handled as if the user entered /send (then ask for contacts from keyboard or entry,
// then ask for an amount).
func (bot *TipBot) keyboardSendHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
enterUserStateData := &EnterUserStateData{
ID: "id",
Type: "CreateSendState",
OiringalCommand: "/send",
}
// set LNURLPayParams in the state of the user
stateDataJson, err := json.Marshal(enterUserStateData)
if err != nil {
log.Errorln(err)
return ctx, err
}
SetUserState(user, bot, lnbits.UserEnterUser, string(stateDataJson))
sendToButtons = bot.makeContactsButtons(ctx)
// if no contact is found (one entry will always be inside, it's the enter user button)
// immediatelly go to the send handler
if len(sendToButtons) == 1 {
m.Text = "/send"
return bot.sendHandler(ctx, m)
}
// Attention! We need to ues the original Telegram.Send command here!
// bot.trySendMessage will replace the keyboard with the default one and we want to send a different keyboard here
// this is suboptimal because Telegram.Send is not rate limited etc. but it's the only way to send a custom keyboard for now
_, err = bot.Telegram.Send(user.Telegram, Translate(ctx, "enterUserMessage"), sendToMenu)
if err != nil {
log.Errorln(err.Error())
}
return ctx, nil
}
// sendHandler invoked when user clicked send on payment confirmation
func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
tx := &SendData{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[acceptSendHandler] %s", err.Error())
return
return ctx, err
}
sendData := sn.(*SendData)
// onnly the correct user can press
if sendData.From.Telegram.ID != c.Sender.ID {
return
return ctx, errors.Create(errors.UnknownError)
}
if !sendData.Active {
log.Errorf("[acceptSendHandler] send not active anymore")
// bot.tryDeleteMessage(c.Message)
return
return ctx, errors.Create(errors.NotActiveError)
}
defer sendData.Set(sendData, bot.Bunt)
@@ -255,7 +298,7 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
if err != nil {
log.Errorln(err.Error())
bot.tryDeleteMessage(c.Message)
return
return ctx, err
}
toUserStrMd := GetUserStrMd(to.Telegram)
fromUserStrMd := GetUserStrMd(from.Telegram)
@@ -272,7 +315,7 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err.Error())
log.Errorln(errmsg)
bot.tryEditMessage(c.Message, i18n.Translate(sendData.LanguageCode, "sendErrorMessage"), &tb.ReplyMarkup{})
return
return ctx, errors.Create(errors.UnknownError)
}
sendData.Inactivate(sendData, bot.Bunt)
@@ -283,7 +326,7 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
// bot.trySendMessage(from.Telegram, fmt.Sprintf(Translate(ctx, "sendSentMessage"), amount, toUserStrMd))
if c.Message.Private() {
// if the command was invoked in private chat
// the edit below was cool, but we need to get rid of the replymarkup inline keyboard thingy for the main menu button update to work (for the new balance)
// the edit below was cool, but we need to get rid of the replymarkup inline keyboard thingy for the main menu to pop up
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd), &tb.ReplyMarkup{})
bot.tryDeleteMessage(c.Message)
bot.trySendMessage(c.Sender, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
@@ -297,11 +340,11 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
bot.trySendMessage(to.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(sendMemo)))
}
return
return ctx, nil
}
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
// reset state immediately
user := LoadUser(ctx)
ResetUserState(user, bot)
@@ -311,15 +354,17 @@ func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) {
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[acceptSendHandler] %s", err.Error())
return
return ctx, err
}
sendData := sn.(*SendData)
// onnly the correct user can press
if sendData.From.Telegram.ID != c.Sender.ID {
return
return ctx, errors.Create(errors.UnknownError)
}
// remove buttons from confirmation message
bot.tryEditMessage(c.Message, i18n.Translate(sendData.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
// delete and send instead of edit for the keyboard to pop up after sending
bot.tryDeleteMessage(c.Message)
bot.trySendMessage(c.Message.Chat, i18n.Translate(sendData.LanguageCode, "sendCancelledMessage"))
sendData.Inactivate(sendData, bot.Bunt)
return ctx, nil
}
+235 -161
View File
File diff suppressed because it is too large Load Diff
+4 -9
View File
@@ -70,7 +70,7 @@ func (bot TipBot) shopItemSettingsMenu(ctx context.Context, shop *Shop, item *Sh
shopItemPriceButton = shopKeyboard.Data("💯 Set price", "shop_itemprice", item.ID)
shopItemDeleteButton = shopKeyboard.Data("🚫 Delete item", "shop_itemdelete", item.ID)
shopItemTitleButton = shopKeyboard.Data("⌨️ Set title", "shop_itemtitle", item.ID)
shopItemAddFileButton = shopKeyboard.Data("💾 Add file", "shop_itemaddfile", item.ID)
shopItemAddFileButton = shopKeyboard.Data("💾 Add files ...", "shop_itemaddfile", item.ID)
shopItemSettingsBackButton = shopKeyboard.Data("⬅️ Back", "shop_itemsettingsback", item.ID)
user := LoadUser(ctx)
buttons := []tb.Row{}
@@ -162,15 +162,14 @@ func (bot *TipBot) getUserShopview(ctx context.Context, user *lnbits.User) (shop
}
func (bot *TipBot) shopViewDeleteAllStatusMsgs(ctx context.Context, user *lnbits.User) (shopView ShopView, err error) {
mutex.Lock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
defer mutex.Unlock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
shopView, err = bot.getUserShopview(ctx, user)
if err != nil {
return
}
deleteStatusMessages(shopView.StatusMessages, bot)
shopView.StatusMessages = make([]*tb.Message, 0)
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
mutex.Unlock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
return
}
@@ -189,6 +188,7 @@ func (bot *TipBot) sendStatusMessage(ctx context.Context, to tb.Recipient, what
// write into cache
mutex.Lock(id)
defer mutex.Unlock(id)
shopView, err := bot.getUserShopview(ctx, user)
if err != nil {
return nil
@@ -196,7 +196,6 @@ func (bot *TipBot) sendStatusMessage(ctx context.Context, to tb.Recipient, what
statusMsg := bot.trySendMessage(to, what, options...)
shopView.StatusMessages = append(shopView.StatusMessages, statusMsg)
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
mutex.Unlock(id)
return statusMsg
}
@@ -238,8 +237,6 @@ func (bot *TipBot) initUserShops(ctx context.Context, user *lnbits.User) (*Shops
// getUserShops returns the Shops for the user
func (bot *TipBot) getUserShops(ctx context.Context, user *lnbits.User) (*Shops, error) {
tx := &Shops{Base: storage.New(storage.ID(fmt.Sprintf("shops-%d", user.Telegram.ID)))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
sn, err := tx.Get(tx, bot.ShopBunt)
if err != nil {
log.Errorf("[getUserShops] User: %s (%d): %s", GetUserStr(user.Telegram), user.Telegram.ID, err)
@@ -272,11 +269,9 @@ func (bot *TipBot) addUserShop(ctx context.Context, user *lnbits.User) (*Shop, e
return shop, nil
}
// getShop returns the Shop for the given ID
// getShop returns the Shop of a given ID
func (bot *TipBot) getShop(ctx context.Context, shopId string) (*Shop, error) {
tx := &Shop{Base: storage.New(storage.ID(shopId))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
// immediatelly set intransaction to block duplicate calls
sn, err := tx.Get(tx, bot.ShopBunt)
if err != nil {
+15 -7
View File
@@ -2,11 +2,13 @@ package telegram
import (
"context"
"errors"
stderrors "errors"
"fmt"
"strconv"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal"
log "github.com/sirupsen/logrus"
@@ -17,20 +19,20 @@ import (
"gorm.io/gorm"
)
func (bot TipBot) startHandler(ctx context.Context, m *tb.Message) {
func (bot TipBot) startHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
if !m.Private() {
return
return ctx, errors.Create(errors.NoPrivateChatError)
}
// ATTENTION: DO NOT CALL ANY HANDLER BEFORE THE WALLET IS CREATED
// WILL RESULT IN AN ENDLESS LOOP OTHERWISE
// bot.helpHandler(m)
log.Printf("[⭐️ /start] New user: %s (%d)\n", GetUserStr(m.Sender), m.Sender.ID)
walletCreationMsg := bot.trySendMessage(m.Sender, Translate(ctx, "startSettingWalletMessage"))
walletCreationMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "startSettingWalletMessage"))
user, err := bot.initWallet(m.Sender)
if err != nil {
log.Errorln(fmt.Sprintf("[startHandler] Error with initWallet: %s", err.Error()))
bot.tryEditMessage(walletCreationMsg, Translate(ctx, "startWalletErrorMessage"))
return
return ctx, err
}
bot.tryDeleteMessage(walletCreationMsg)
ctx = context.WithValue(ctx, "user", user)
@@ -42,17 +44,19 @@ func (bot TipBot) startHandler(ctx context.Context, m *tb.Message) {
if len(m.Sender.Username) == 0 {
bot.trySendMessage(m.Sender, Translate(ctx, "startNoUsernameMessage"), tb.NoPreview)
}
return
return ctx, nil
}
func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
user, err := GetUser(tguser, bot)
if errors.Is(err, gorm.ErrRecordNotFound) {
if stderrors.Is(err, gorm.ErrRecordNotFound) {
user = &lnbits.User{Telegram: tguser}
err = bot.createWallet(user)
if err != nil {
return user, err
}
// set user initialized
user, err := GetUser(tguser, bot)
user.Initialized = true
err = UpdateUserRecord(user, bot)
if err != nil {
@@ -99,7 +103,11 @@ func (bot TipBot) createWallet(user *lnbits.User) error {
return err
}
user.Wallet = &wallet[0]
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
user.AnonIDSha256 = str.AnonIdSha256(user)
user.UUID = str.UUIDSha256(user)
user.Initialized = false
user.CreatedAt = time.Now()
err = UpdateUserRecord(user, bot)
+1 -1
View File
@@ -6,7 +6,7 @@ import (
tb "gopkg.in/lightningtipbot/telebot.v2"
)
type StateCallbackMessage map[lnbits.UserStateKey]func(ctx context.Context, m *tb.Message)
type StateCallbackMessage map[lnbits.UserStateKey]func(ctx context.Context, m *tb.Message) (context.Context, error)
var stateCallbackMessage StateCallbackMessage
+14 -3
View File
@@ -42,6 +42,7 @@ func (bot TipBot) trySendMessage(to tb.Recipient, what interface{}, options ...i
log.Errorf("[trySendMessage] error converting message recipient to int64: %v", err)
return
}
log.Tracef("[trySendMessage] chatId: %d", chatId)
msg, err = bot.Telegram.Send(to, what, bot.appendMainMenu(chatId, to, options)...)
if err != nil {
log.Warnln(err.Error())
@@ -49,6 +50,15 @@ func (bot TipBot) trySendMessage(to tb.Recipient, what interface{}, options ...i
return
}
func (bot TipBot) trySendMessageEditable(to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
rate.CheckLimit(to)
msg, err := bot.Telegram.Send(to, what, options...)
if err != nil {
log.Warnln(err.Error())
}
return
}
func (bot TipBot) tryReplyMessage(to *tb.Message, what interface{}, options ...interface{}) (msg *tb.Message) {
rate.CheckLimit(to)
msg, err := bot.Telegram.Reply(to, what, bot.appendMainMenu(to.Chat.ID, to, options)...)
@@ -59,15 +69,16 @@ func (bot TipBot) tryReplyMessage(to *tb.Message, what interface{}, options ...i
}
func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...interface{}) (msg *tb.Message, err error) {
// do not attempt edit if the message did not change
// get a sig for the rate limiter
sig, chat := to.MessageSig()
if chat != 0 {
sig = strconv.FormatInt(chat, 10)
}
rate.CheckLimit(sig)
_, chatId := to.MessageSig()
msg, err = bot.Telegram.Edit(to, what, bot.appendMainMenu(chatId, to, options)...)
log.Tracef("[tryEditMessage] sig: %s, chatId: %d", sig, chatId)
msg, err = bot.Telegram.Edit(to, what, options...)
if err != nil {
log.Warnln(err.Error())
}
+18 -20
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
@@ -12,16 +13,15 @@ import (
tb "gopkg.in/lightningtipbot/telebot.v2"
)
func (bot *TipBot) anyTextHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) anyTextHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
if m.Chat.Type != tb.ChatPrivate {
return
return ctx, errors.Create(errors.NoPrivateChatError)
}
// check if user is in Database, if not, initialize wallet
user := LoadUser(ctx)
if user.Wallet == nil || !user.Initialized {
bot.startHandler(ctx, m)
return
return bot.startHandler(ctx, m)
}
// check if the user clicked on the balance button
@@ -30,26 +30,24 @@ func (bot *TipBot) anyTextHandler(ctx context.Context, m *tb.Message) {
// overwrite the message text so it doesn't cause an infinite loop
// because balanceHandler calls anyTextHAndler...
m.Text = ""
bot.balanceHandler(ctx, m)
return
return bot.balanceHandler(ctx, m)
}
// could be an invoice
anyText := strings.ToLower(m.Text)
if lightning.IsInvoice(anyText) {
m.Text = "/pay " + anyText
bot.payHandler(ctx, m)
return
return bot.payHandler(ctx, m)
}
if lightning.IsLnurl(anyText) {
m.Text = "/lnurl " + anyText
bot.lnurlHandler(ctx, m)
return
return bot.lnurlHandler(ctx, m)
}
if c := stateCallbackMessage[user.StateKey]; c != nil {
c(ctx, m)
return c(ctx, m)
//ResetUserState(user, bot)
}
return ctx, nil
}
type EnterUserStateData struct {
@@ -86,19 +84,19 @@ func (bot *TipBot) askForUser(ctx context.Context, id string, eventType string,
// enterAmountHandler is invoked in anyTextHandler when the user needs to enter an amount
// the amount is then stored as an entry in the user's stateKey in the user database
// any other handler that relies on this, needs to load the resulting amount from the database
func (bot *TipBot) enterUserHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) enterUserHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
user := LoadUser(ctx)
if user.Wallet == nil {
return // errors.New("user has no wallet"), 0
return ctx, errors.Create(errors.UserNoWalletError)
}
if !(user.StateKey == lnbits.UserEnterUser) {
ResetUserState(user, bot)
return // errors.New("user state does not match"), 0
return ctx, errors.Create(errors.InvalidSyntaxError)
}
if len(m.Text) < 4 || strings.HasPrefix(m.Text, "/") {
if len(m.Text) < 4 || strings.HasPrefix(m.Text, "/") || m.Text == SendMenuCommandEnter {
ResetUserState(user, bot)
return
return ctx, errors.Create(errors.InvalidSyntaxError)
}
var EnterUserStateData EnterUserStateData
@@ -106,7 +104,7 @@ func (bot *TipBot) enterUserHandler(ctx context.Context, m *tb.Message) {
if err != nil {
log.Errorf("[EnterUserHandler] %s", err.Error())
ResetUserState(user, bot)
return
return ctx, err
}
userstr := m.Text
@@ -116,10 +114,10 @@ func (bot *TipBot) enterUserHandler(ctx context.Context, m *tb.Message) {
switch EnterUserStateData.Type {
case "CreateSendState":
m.Text = fmt.Sprintf("/send %s", userstr)
bot.sendHandler(ctx, m)
return
return bot.sendHandler(ctx, m)
default:
ResetUserState(user, bot)
return
return ctx, errors.Create(errors.InvalidSyntaxError)
}
return ctx, nil
}
+11 -10
View File
@@ -3,6 +3,7 @@ package telegram
import (
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"strings"
"time"
@@ -30,12 +31,12 @@ func TipCheckSyntax(ctx context.Context, m *tb.Message) (bool, string) {
return true, ""
}
func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
// check and print all commands
bot.anyTextHandler(ctx, m)
user := LoadUser(ctx)
if user.Wallet == nil {
return
return ctx, fmt.Errorf("user has no wallet")
}
// only if message is a reply
@@ -43,13 +44,13 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
bot.tryDeleteMessage(m)
bot.trySendMessage(m.Sender, helpTipUsage(ctx, Translate(ctx, "tipDidYouReplyMessage")))
bot.trySendMessage(m.Sender, Translate(ctx, "tipInviteGroupMessage"))
return
return ctx, errors.Create(errors.NoReplyMessageError)
}
if ok, err := TipCheckSyntax(ctx, m); !ok {
bot.trySendMessage(m.Sender, helpTipUsage(ctx, err))
NewMessage(m, WithDuration(0, bot))
return
return ctx, errors.Create(errors.InvalidSyntaxError)
}
// get tip amount
@@ -60,12 +61,12 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, helpTipUsage(ctx, Translate(ctx, "tipValidAmountMessage")))
log.Warnln(errmsg)
return
return ctx, errors.Create(errors.InvalidAmountError)
}
err = bot.parseCmdDonHandler(ctx, m)
if err == nil {
return
return ctx, fmt.Errorf("invalid parseCmdDonHandler")
}
// TIP COMMAND IS VALID
from := LoadUser(ctx)
@@ -74,7 +75,7 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
if from.Telegram.ID == to.Telegram.ID {
NewMessage(m, WithDuration(0, bot))
bot.trySendMessage(m.Sender, Translate(ctx, "tipYourselfMessage"))
return
return ctx, fmt.Errorf("cannot tip yourself")
}
toUserStrMd := GetUserStrMd(to.Telegram)
@@ -88,7 +89,7 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
if err != nil {
errmsg := fmt.Errorf("[/tip] Error: Could not create wallet for %s", toUserStr)
log.Errorln(errmsg)
return
return ctx, fmt.Errorf("could not create wallet for %s", toUserStr)
}
}
@@ -112,7 +113,7 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
bot.trySendMessage(m.Sender, fmt.Sprintf("%s %s", Translate(ctx, "tipErrorMessage"), err))
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err.Error())
log.Warnln(errMsg)
return
return ctx, fmt.Errorf("could not create wallet for %s", toUserStr)
}
// update tooltip if necessary
@@ -134,5 +135,5 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
}
// delete the tip message after a few seconds, this is default behaviour
NewMessage(m, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
return
return ctx, nil
}
@@ -15,7 +15,6 @@ import (
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
log "github.com/sirupsen/logrus"
tb "gopkg.in/lightningtipbot/telebot.v2"
)
@@ -82,7 +81,7 @@ func (bot TipBot) createTipjar(ctx context.Context, text string, sender *tb.User
if len(memo) > 0 {
inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineTipjarAppendMemo"), memo)
}
id := fmt.Sprintf("inl-tipjar-%d-%d-%s", sender.ID, amount, RandStringRunes(5))
id := fmt.Sprintf("tipjar:%s:%d", RandStringRunes(10), amount)
return &InlineTipjar{
Base: storage.New(storage.ID(id)),
@@ -161,7 +160,7 @@ func (bot TipBot) makeQueryTipjar(ctx context.Context, q *tb.Query, query bool)
}
func (bot TipBot) makeTipjarKeyboard(ctx context.Context, inlineTipjar *InlineTipjar) *tb.ReplyMarkup {
// inlineTipjarMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
inlineTipjarMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
// slice of buttons
buttons := make([]tb.Btn, 0)
cancelInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_tipjar_inline", inlineTipjar.ID)
@@ -174,29 +173,29 @@ func (bot TipBot) makeTipjarKeyboard(ctx context.Context, inlineTipjar *InlineTi
return inlineTipjarMenu
}
func (bot TipBot) tipjarHandler(ctx context.Context, m *tb.Message) {
func (bot TipBot) tipjarHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
bot.anyTextHandler(ctx, m)
if m.Private() {
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineTipjarHelpText"), Translate(ctx, "inlineTipjarHelpTipjarInGroup")))
return
return ctx, errors.Create(errors.NoPrivateChatError)
}
ctx = bot.mapTipjarLanguage(ctx, m.Text)
inlineTipjar, err := bot.makeTipjar(ctx, m, false)
if err != nil {
log.Errorf("[tipjar] %s", err.Error())
return
return ctx, err
}
toUserStr := GetUserStr(m.Sender)
bot.trySendMessage(m.Chat, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
log.Infof("[tipjar] %s created tipjar %s: %d sat (%d per user)", toUserStr, inlineTipjar.ID, inlineTipjar.Amount, inlineTipjar.PerUserAmount)
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
return ctx, inlineTipjar.Set(inlineTipjar, bot.Bunt)
}
func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) {
func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) (context.Context, error) {
inlineTipjar, err := bot.makeQueryTipjar(ctx, q, false)
if err != nil {
// log.Errorf("[tipjar] %s", err.Error())
return
return ctx, err
}
urls := []string{
queryImage,
@@ -227,13 +226,15 @@ func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) {
})
if err != nil {
log.Errorln(err)
return ctx, err
}
return ctx, nil
}
func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
from := LoadUser(ctx)
if from.Wallet == nil {
return
return ctx, errors.Create(errors.UserNoWalletError)
}
tx := &InlineTipjar{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
@@ -241,27 +242,31 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
// log.Errorf("[tipjar] %s", err.Error())
return
return ctx, err
}
inlineTipjar := fn.(*InlineTipjar)
to := inlineTipjar.To
if !inlineTipjar.Active {
log.Errorf(fmt.Sprintf("[tipjar] tipjar %s inactive.", inlineTipjar.ID))
return
bot.tryEditMessage(c.Message, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
return ctx, errors.Create(errors.NotActiveError)
}
if from.Telegram.ID == to.Telegram.ID {
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
return
return ctx, errors.Create(errors.SelfPaymentError)
}
// // check if to user has already given to the tipjar
for _, a := range inlineTipjar.From {
if a.Telegram.ID == from.Telegram.ID {
// to user is already in To slice, has taken from facuet
// log.Infof("[tipjar] %s already gave to tipjar %s", GetUserStr(to.Telegram), inlineTipjar.ID)
return
return ctx, errors.Create(errors.UnknownError)
}
}
defer inlineTipjar.Set(inlineTipjar, bot.Bunt)
if inlineTipjar.GivenAmount < inlineTipjar.Amount {
toUserStrMd := GetUserStrMd(to.Telegram)
fromUserStrMd := GetUserStrMd(from.Telegram)
@@ -278,7 +283,7 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
errMsg := fmt.Sprintf("[tipjar] Transaction failed: %s", err.Error())
log.Errorln(errMsg)
return
return ctx, errors.New(errors.UnknownError, err)
}
log.Infof("[💸 tipjar] Tipjar %s from %s to %s (%d sat).", inlineTipjar.ID, fromUserStr, toUserStr, inlineTipjar.PerUserAmount)
@@ -307,9 +312,6 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
if len(memo) > 0 {
inlineTipjar.Message = inlineTipjar.Message + fmt.Sprintf(i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarAppendMemo"), memo)
}
// if inlineTipjar.UserNeedsWallet {
// inlineTipjar.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
// }
// update message
log.Infoln(inlineTipjar.Message)
bot.tryEditMessage(c.Message, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
@@ -322,30 +324,49 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
inlineTipjar.Amount,
inlineTipjar.NGiven,
)
// if inlineTipjar.UserNeedsWallet {
// inlineTipjar.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
// }
bot.tryEditMessage(c.Message, inlineTipjar.Message)
// send update to tipjar creator
if inlineTipjar.Active && inlineTipjar.To.Telegram.ID != 0 {
bot.trySendMessage(inlineTipjar.To.Telegram, listTipjarGivers(inlineTipjar))
}
inlineTipjar.Active = false
}
return ctx, nil
}
func (bot *TipBot) cancelInlineTipjarHandler(ctx context.Context, c *tb.Callback) {
func (bot *TipBot) cancelInlineTipjarHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
tx := &InlineTipjar{Base: storage.New(storage.ID(c.Data))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[cancelInlineTipjarHandler] %s", err.Error())
return
return ctx, err
}
inlineTipjar := fn.(*InlineTipjar)
if c.Sender.ID == inlineTipjar.To.Telegram.ID {
bot.tryEditMessage(c.Message, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
// set the inlineTipjar inactive
inlineTipjar.Active = false
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
if c.Sender.ID != inlineTipjar.To.Telegram.ID {
return ctx, errors.Create(errors.UnknownError)
}
return
bot.tryEditMessage(c.Message, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
// send update to tipjar creator
if inlineTipjar.Active && inlineTipjar.To.Telegram.ID != 0 {
bot.trySendMessage(inlineTipjar.To.Telegram, listTipjarGivers(inlineTipjar))
}
// set the inlineTipjar inactive
inlineTipjar.Active = false
return ctx, inlineTipjar.Set(inlineTipjar, bot.Bunt)
}
func listTipjarGivers(inlineTipjar *InlineTipjar) string {
var from_str string
from_str = fmt.Sprintf("🍯 *Tipjar summary*\n\nMemo: %s\nCapacity: %d sat\nGivers: %d\nCollected: %d sat\n\n*Givers:*\n\n", inlineTipjar.Memo, inlineTipjar.Amount, inlineTipjar.NGiven, inlineTipjar.GivenAmount)
from_str += "```\n"
for _, from := range inlineTipjar.From {
from_str += fmt.Sprintf("%s\n", GetUserStr(from.Telegram))
}
from_str += "```"
return from_str
}
+20 -1
View File
@@ -3,6 +3,7 @@ package telegram
import (
"errors"
"fmt"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
@@ -83,7 +84,7 @@ func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
}
// msat to sat
amount = int64(wallet.Balance) / 1000
log.Infof("[GetUserBalance] %s's balance: %d sat\n", GetUserStr(user.Telegram), amount)
log.Debugf("[GetUserBalance] %s's balance: %d sat\n", GetUserStr(user.Telegram), amount)
// update user balance in cache
bot.Cache.Set(
@@ -95,6 +96,10 @@ func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
}
func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, error) {
// failsafe: do not create wallet for existing user
if _, exists := bot.UserExists(tbUser); exists {
return nil, fmt.Errorf("user already exists")
}
user := &lnbits.User{Telegram: tbUser}
userStr := GetUserStr(tbUser)
log.Printf("[CreateWalletForTelegramUser] Creating wallet for user %s ... ", userStr)
@@ -104,6 +109,7 @@ func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, e
log.Errorln(errmsg)
return user, err
}
// todo: remove this. we're doing this already in bot.createWallet().
err = UpdateUserRecord(user, *bot)
if err != nil {
return nil, err
@@ -119,3 +125,16 @@ func (bot *TipBot) UserExists(user *tb.User) (*lnbits.User, bool) {
}
return lnbitUser, true
}
func (bot *TipBot) UserIsBanned(user *lnbits.User) bool {
// do not respond to banned users
if user.Wallet == nil {
log.Tracef("[UserIsBanned] User %s has no wallet.\n", GetUserStr(user.Telegram))
return false
}
if strings.HasPrefix(user.Wallet.Adminkey, "banned") || strings.Contains(user.Wallet.Adminkey, "_") {
log.Debugf("[UserIsBanned] User %s is banned. Not responding.", GetUserStr(user.Telegram))
return true
}
return false
}
+36 -13
View File
@@ -1,16 +1,18 @@
package main
import (
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/api"
"github.com/LightningTipBot/LightningTipBot/internal/api/admin"
"github.com/LightningTipBot/LightningTipBot/internal/lndhub"
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"net/http"
"runtime/debug"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/gorilla/mux"
_ "net/http/pprof"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits/webhook"
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
"github.com/LightningTipBot/LightningTipBot/internal/price"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
log "github.com/sirupsen/logrus"
@@ -18,7 +20,7 @@ import (
// setLogger will initialize the log format
func setLogger() {
log.SetLevel(log.TraceLevel)
log.SetLevel(log.DebugLevel)
customFormatter := new(log.TextFormatter)
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
customFormatter.FullTimestamp = true
@@ -28,18 +30,39 @@ func setLogger() {
func main() {
// set logger
setLogger()
router := mux.NewRouter()
router.PathPrefix("/debug/pprof/").Handler(http.DefaultServeMux)
router.Handle("/mutex", http.HandlerFunc(mutex.ServeHTTP))
router.Handle("/mutex/unlock/{id}", http.HandlerFunc(mutex.UnlockHTTP))
go http.ListenAndServe("0.0.0.0:6060", router)
defer withRecovery()
bot := telegram.NewBot()
webhook.NewServer(&bot)
lnurl.NewServer(&bot)
price.NewPriceWatcher().Start()
bot := telegram.NewBot()
startApiServer(&bot)
bot.Start()
}
func startApiServer(bot *telegram.TipBot) {
// start internal webhook server
webhook.NewServer(bot)
// start external api server
s := api.NewServer(internal.Configuration.Bot.LNURLServerUrl.Host)
// append lnurl handler functions
lnUrl := lnurl.New(bot)
s.AppendRoute("/.well-known/lnurlp/{username}", lnUrl.Handle, http.MethodGet)
s.AppendRoute("/@{username}", lnUrl.Handle, http.MethodGet)
// append lndhub handler functions
hub := lndhub.New(bot)
s.AppendRoute(`/lndhub/ext/{.*}`, hub.Handle)
s.AppendRoute(`/lndhub/ext`, hub.Handle)
// start internal admin server
adminService := admin.New(bot)
internalAdminServer := api.NewServer("0.0.0.0:6060")
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.PathPrefix("/debug/pprof/", http.DefaultServeMux)
}
func withRecovery() {
if r := recover(); r != nil {
Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 39 KiB

+8 -1
View File
@@ -237,6 +237,13 @@ lnurlHelpText = """📖 Ups, das hat nicht geklappt. %s
*Befehl:* `/lnurl [betrag] <lnurl>`
*Beispiel:* `/lnurl LNURL1DP68GUR...`"""
# LNURL LOGIN
confirmLnurlAuthMessager = """Möchtest du dich bei %s einloggen?"""
lnurlSuccessfulLogin = """✅ Login erfolgreich."""
loginButtonMessage = """✅ Login"""
loginCancelledMessage = """🚫 Login abgebrochen."""
# LNURL WITHDRAW
confirmLnurlWithdrawMessage = """Möchtest du diese Abhebung tätigen?\n\n💸 Betrag: %d sat"""
@@ -262,7 +269,7 @@ inlineQueryFaucetDescription = """Befehl: @%s faucet <gesamt> <pro_user>"""
inlineResultFaucetTitle = """🚰 Erzeuge einen %d sat Zapfhahn."""
inlineResultFaucetDescription = """👉 Klicke hier um den Zapfhahn in diesen Chat zu senden."""
inlineFaucetMessage = """Drücke ✅ um %d sat aus diesem Zapfhahn zu zapfen.
inlineFaucetMessage = """Drücke ✅ um %d sat aus %s's Zapfhahn zu zapfen.
🚰 Verbleibend: %d/%d sat (%d/%d gezapft)
%s"""
+13 -5
View File
@@ -82,7 +82,7 @@ _This bot charges no fees but costs Satoshis to operate. If you like the bot, pl
*/help* 📖 Read this help."""
infoHelpMessage = """ℹ️ *Info*"""
infoYourLightningAddress = """Your Lightning Address is `%s`"""
infoYourLightningAddress = """Your Lightning address is `%s`"""
basicsMessage = """🧡 *Bitcoin*
_Bitcoin is the currency of the internet. It is permissionless and decentralized and has no masters and no controling authority. Bitcoin is sound money that is faster, more secure, and more inclusive than the legacy financial system._
@@ -195,10 +195,10 @@ invoiceHelpText = """📖 Oops, that didn't work. %s
paymentCancelledMessage = """🚫 Payment cancelled."""
invoicePaidMessage = """⚡️ Payment sent."""
invoicePublicPaidMessage = """⚡️ Payment sent by %s."""
invalidInvoiceHelpMessage = """Did you enter a valid Lightning invoice? Try /send if you want to send to a Telegram user or Lightning address."""
invalidInvoiceHelpMessage = """Did you enter a valid Lightning invoice? Try /send if you want to send to a Telegram user or to a Lightning address."""
invoiceNoAmountMessage = """🚫 Can't pay invoices without an amount."""
insufficientFundsMessage = """🚫 Insufficient funds. You have %d sat but you need at least %d sat."""
feeReserveMessage = """⚠️ Sending your entire balance might fail because of network fees. If it fails, try sending a bit less."""
feeReserveMessage = """⚠️ Sending your entire balance might fail because of network fees. Reserve at least 1% for fees."""
invoicePaymentFailedMessage = """🚫 Payment failed: %s"""
invoiceUndefinedErrorMessage = """Could not pay invoice."""
confirmPayInvoiceMessage = """Do you want to send this payment?\n\n💸 Amount: %d sat"""
@@ -241,6 +241,13 @@ lnurlHelpText = """📖 Oops, that didn't work. %s
*Usage:* `/lnurl [amount] <lnurl>`
*Example:* `/lnurl LNURL1DP68GUR...`"""
# LNURL LOGIN
confirmLnurlAuthMessager = """Do you want to login to %s?"""
lnurlSuccessfulLogin = """✅ Login successful."""
loginButtonMessage = """✅ Login"""
loginCancelledMessage = """🚫 Login cancelled."""
# LNURL WITHDRAW
confirmLnurlWithdrawMessage = """Do you want to make this withdrawal?\n\n💸 Amount: %d sat"""
@@ -267,7 +274,7 @@ inlineQueryFaucetDescription = """Usage: @%s faucet <capacity> <per_user>"""
inlineResultFaucetTitle = """🚰 Create a %d sat faucet."""
inlineResultFaucetDescription = """👉 Click here to create a faucet in this chat."""
inlineFaucetMessage = """Press ✅ to collect %d sat from this faucet.
inlineFaucetMessage = """Press ✅ to collect %d sat from %s's faucet.
🚰 Remaining: %d/%d sat (given to %d/%d users)
%s"""
@@ -275,11 +282,12 @@ inlineFaucetEndedMessage = """🚰 Faucet empty 🍺\n\n🏅 %d s
inlineFaucetAppendMemo = """\n✉️ %s"""
inlineFaucetCreateWalletMessage = """Chat with %s 👈 to manage your wallet."""
inlineFaucetCancelledMessage = """🚫 Faucet cancelled."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Peruser amount not divisor of capacity."""
inlineFaucetInvalidPeruserAmountMessage = """🚫 Peruser amount not divisor of capacity or too low (min 5 sat)."""
inlineFaucetInvalidAmountMessage = """🚫 Invalid amount."""
inlineFaucetSentMessage = """🚰 %d sat sent to %s."""
inlineFaucetReceivedMessage = """🚰 %s sent you %d sat."""
inlineFaucetHelpFaucetInGroup = """Create a faucet in a group with the bot inside or use 👉 inline command (/advanced for more)."""
inlineFaucetAlreadyTookMessage = """🚫 You already took from this faucet."""
inlineFaucetHelpText = """📖 Oops, that didn't work. %s
*Usage:* `/faucet <capacity> <per_user>`
+8 -1
View File
@@ -237,6 +237,13 @@ lnurlHelpText = """📖 Oops, eso no funcionó. %s
*Uso:* `/lnurl [monto] <lnurl>`
*Ejemplo:* `/lnurl LNURL1DP68GUR...`"""
# LNURL LOGIN
confirmLnurlAuthMessager = """¿Desea iniciar sesión en %s?"""
lnurlSuccessfulLogin = """✅ Inicio de sesión exitoso."""
loginButtonMessage = """✅ Inicio de sesión"""
loginCancelledMessage = """🚫 Inicio de sesión cancelado."""
# LNURL WITHDRAW
confirmLnurlWithdrawMessage = """¿Desea realizar este retiro?\n\n💸 Monto: %d sat"""
@@ -262,7 +269,7 @@ inlineQueryFaucetDescription = """Uso: @%s faucet <capacidad> <por_usuario>"""
inlineResultFaucetTitle = """🚰 Crear un grifo %d sat."""
inlineResultFaucetDescription = """👉 Haz clic aquí para crear un grifo en este chat."""
inlineFaucetMessage = """Pulsa ✅ para cobrar %d sat de este grifo.
inlineFaucetMessage = """Pulsa ✅ para cobrar %d sat de este grifo de %s.
🚰 Restante: %d/%d sat (dado a %d/%d usuarios)
%s"""
+1 -1
View File
@@ -254,7 +254,7 @@ inlineQueryFaucetDescription = """Usage: @%s faucet <capacité> <par_utilisateu
inlineResultFaucetTitle = """🚰 Création d'un %d sat faucet."""
inlineResultFaucetDescription = """👉 Appuyez ici pour créer un faucet dans ce chat."""
inlineFaucetMessage = """Appuyez sur ✅ pour collecter %d sat de ce faucet.
inlineFaucetMessage = """Appuyez sur ✅ pour collecter %d sat de ce faucet de %s.
🚰 Restant: %d/%d sat (envoyé à %d/%d utilisateurs)
%s"""
+1 -1
View File
@@ -262,7 +262,7 @@ inlineQueryFaucetDescription = """Penggunaan: @%s faucet <kapasitas> <per_pengg
inlineResultFaucetTitle = """🚰 Buat sebuah keran %d sat."""
inlineResultFaucetDescription = """👉 Pencet disini untuk membuat sebuah keran di percakapan ini."""
inlineFaucetMessage = """Tekan ✅ untuk mengambil %d sat dari keran ini.
inlineFaucetMessage = """Tekan ✅ untuk mengambil %d sat dari keran ini %s.
🚰 Tersisa: %d/%d sat (diberikan kepada %d/%d pengguna)
%s"""
+1 -1
View File
@@ -254,7 +254,7 @@ inlineQueryFaucetDescription = """Sintassi: @%s faucet <totale> <per_utente>"""
inlineResultFaucetTitle = """🚰 Crea una distribuzione per un totale di %d sat."""
inlineResultFaucetDescription = """👉 Clicca qui per creare una distribuzione di fondi in questa chat."""
inlineFaucetMessage = """Premi ✅ per riscuotere %d sat da questa distribuzione.
inlineFaucetMessage = """Premi ✅ per riscuotere %d sat da questa distribuzione da %s.
🚰 Rimanente: %d/%d sat (distribuiti a %d/%d utenti)
%s"""
+1 -1
View File
@@ -262,7 +262,7 @@ inlineQueryFaucetDescription = """Gebruik: @%s faucet <capacity> <per_user>"""
inlineResultFaucetTitle = """🚰 Maak een %d sat kraan."""
inlineResultFaucetDescription = """👉 Klik hier om een kraan in deze chat te maken.."""
inlineFaucetMessage = """Druk op ✅ om %d sat te verzamelen van deze kraan.
inlineFaucetMessage = """Druk op ✅ om %d sat te verzamelen van deze kraan van %s.
🚰 Remaining: %d/%d sat (given to %d/%d users)
%s"""
+9 -2
View File
@@ -78,7 +78,7 @@ _Este bot não cobra nenhuma comissão, mas custa Satoshis para funcionar. Se vo
*/help* 📖 Ler esta ajuda."""
infoHelpMessage = """ℹ️ *Info*"""
infoYourLightningAddress = """Seu Lightning Address _(Endereço Lightning)_ é `%s`."""
infoYourLightningAddress = """Seu Lightning address _(endereço lightning)_ é `%s`."""
basicsMessage = """🧡 *Bitcoin*
_Bitcoin é a moeda da Internet. É uma moeda sem permissão, descentralizada, sem proprietários e sem autoridade de controle. Bitcoin é dinheiro sólido, mais rápido, mais seguro e mais inclusivo do que o sistema financeiro fiat._
@@ -237,6 +237,13 @@ lnurlHelpText = """📖 Opa, isso não funcionou. %s
*Uso:* `/lnurl [quantidade] <lnurl>`
*Exemplo:* `/lnurl LNURL1DP68GUR...`"""
# LNURL LOGIN
confirmLnurlAuthMessager = """Você quer fazer login em %s?"""
lnurlSuccessfulLogin = """✅ Login com sucesso."""
loginButtonMessage = """✅ Login"""
loginCancelledMessage = """🚫 Login cancelado."""
# LNURL WITHDRAW
confirmLnurlWithdrawMessage = """Você quer fazer esse saque?\n💸 Quantia: %d sat"""
@@ -262,7 +269,7 @@ inlineQueryFaucetDescription = """Uso: @%s faucet <capacidade> <por_usuário>""
inlineResultFaucetTitle = """🚰 Criar uma torneira %d sat."""
inlineResultFaucetDescription = """👉 Aperte aqui para criar uma torneira neste chat."""
inlineFaucetMessage = """Aperte ✅ para coletar %d sat desta torneira.
inlineFaucetMessage = """Aperte ✅ para coletar %d sat desta torneira de %s.
🚰 Restante: %d/%d sat (para %d/%d usuários)
%s"""
+1 -1
View File
@@ -266,7 +266,7 @@ inlineQueryFaucetDescription = """Использование: @%s faucet <capac
inlineResultFaucetTitle = """🚰 Создать %d sat криптораздачу."""
inlineResultFaucetDescription = """👉 Нажмите здесь, чтобы создать криптораздачу в этом чате."""
inlineFaucetMessage = """Нажмите ✅, чтобы забрать %d sat из этой криптораздачи.
inlineFaucetMessage = """Нажмите ✅, чтобы забрать %d sat из этой криптораздачи от %s.
🚰 Осталось: %d/%d sat (отдано %d/%d пользователям)
%s"""
+1 -1
View File
@@ -254,7 +254,7 @@ inlineQueryFaucetDescription = """Komut: @%s faucet <toplam> <kullanıcı_başı
inlineResultFaucetTitle = """🚰 Bir %d sat Fıçı oluştur."""
inlineResultFaucetDescription = """👉 Fıçı’yı bu sohbete göndermek için tıkla."""
inlineFaucetMessage = """✅ butonuna basarak Fıçıdan %d sat çek.
inlineFaucetMessage = """✅ butonuna basarak %s'in Fıçıdan %d sat çek.
🚰 Kalan: %d/%d sat (%d/%d çekildi)
%s"""