Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc650ac23d | ||
|
|
e82b933f31 | ||
|
|
0509d107d7 | ||
|
|
ca5dc07d4e | ||
|
|
cc034d5fcf |
+1
-3
@@ -2,7 +2,6 @@ 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"
|
||||
@@ -15,5 +14,4 @@ lnbits:
|
||||
database:
|
||||
db_path: "data/bot.db"
|
||||
buntdb_path: "data/bunt.db"
|
||||
transactions_path: "data/transactions.db"
|
||||
shop_buntdb_path: "data/shop.db"
|
||||
transactions_path: "data/transactions.db"
|
||||
@@ -4,28 +4,21 @@ 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/go-lnurl v1.4.0
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0
|
||||
github.com/gorilla/mux v1.8.0
|
||||
github.com/imroc/req v0.3.0
|
||||
github.com/jinzhu/configor v1.2.1
|
||||
github.com/makiuchi-d/gozxing v0.0.2
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect
|
||||
github.com/nicksnyder/go-i18n/v2 v2.1.2
|
||||
github.com/orcaman/concurrent-map v1.0.0
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible
|
||||
github.com/sethvargo/go-limiter v0.7.2
|
||||
github.com/sirupsen/logrus v1.6.0
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||
github.com/tidwall/buntdb v1.2.7
|
||||
github.com/tidwall/gjson v1.10.2
|
||||
golang.org/x/text v0.3.5
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211217193303-c005cce171ac
|
||||
gopkg.in/tucnak/telebot.v2 v2.3.5
|
||||
gorm.io/driver/sqlite v1.1.4
|
||||
gorm.io/gorm v1.21.12
|
||||
)
|
||||
|
||||
// replace gopkg.in/lightningtipbot/telebot.v2 => ../telebot
|
||||
|
||||
@@ -83,7 +83,6 @@ 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=
|
||||
@@ -138,10 +137,6 @@ github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLi
|
||||
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
|
||||
github.com/fiatjaf/go-lnurl v1.4.0 h1:hVFEEJD2A9D6ojEcqLyD54CM2ZJ9Tzs2jNKw/GNq52A=
|
||||
github.com/fiatjaf/go-lnurl v1.4.0/go.mod h1:BqA8WXAOzntF7Z3EkVO7DfP4y5rhWUmJ/Bu9KBke+rs=
|
||||
github.com/fiatjaf/go-lnurl v1.8.3 h1:ONQUQsXIZKkzrzax2SMUr5W0PreluhO4tct1JM0V/MA=
|
||||
github.com/fiatjaf/go-lnurl v1.8.3/go.mod h1:0PPdV2GFnJK97ztksEIwrcEUVTothAKJsmzqPphAQhs=
|
||||
github.com/fiatjaf/go-lnurl v1.8.4 h1:uVH8833lVgvNqW3S0qr0I8VsIId5mVw0lE0KnEjgh/o=
|
||||
github.com/fiatjaf/go-lnurl v1.8.4/go.mod h1:0PPdV2GFnJK97ztksEIwrcEUVTothAKJsmzqPphAQhs=
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0 h1:HigjqNH+ApiO6gm7RV23jXNFuvwq+zgsWl4BJAfPWwE=
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0/go.mod h1:2qdTT95b8Z4dfuxiZxXuJ1M7bQ9CrLieEA1DKC50q6s=
|
||||
github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw=
|
||||
@@ -260,7 +255,6 @@ 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=
|
||||
@@ -365,8 +359,6 @@ 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=
|
||||
@@ -401,8 +393,6 @@ github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxS
|
||||
github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw=
|
||||
github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4=
|
||||
github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4=
|
||||
github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HDbW65HOY=
|
||||
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
|
||||
github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM=
|
||||
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
|
||||
@@ -459,8 +449,6 @@ github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQD
|
||||
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
|
||||
github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E=
|
||||
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
|
||||
github.com/sethvargo/go-limiter v0.7.2 h1:FgC4N7RMpV5gMrUdda15FaFTkQ/L4fEqM7seXMs4oO8=
|
||||
github.com/sethvargo/go-limiter v0.7.2/go.mod h1:C0kbSFbiriE5k2FFOe18M1YZbAR2Fiwf72uGu0CXCcU=
|
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
|
||||
github.com/sirupsen/logrus v1.2.0 h1:juTguoYk5qI21pwyTXY3B3Y5cOTH3ZUyZCg1v/mihuo=
|
||||
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
||||
@@ -657,9 +645,7 @@ golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ=
|
||||
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2 h1:+DCIGbF/swA92ohVg0//6X2IVY3KZs6p9mix0ziNYJM=
|
||||
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0 h1:/5xXl8Y5W96D+TtHSlonuFqGHIWVuyCkGJLwGh9JJFs=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
@@ -726,18 +712,6 @@ gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o=
|
||||
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.3.5 h1:TdMJTlG8kvepsvZdy/gPeYEBdwKdwFFjH1AQTua9BOU=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.3.5/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.1 h1:bUOFHtHhuhPekjHGe1Q1BmITvtBLdQI4yjSMC405KcU=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.1/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201070229-f317e8453e9f h1:BnYlAEmRJi8YEcSbXO6PlAVwl7WpKJvMqkijHZmO8Gw=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201070229-f317e8453e9f/go.mod h1:lUH49SRidDcQGyXPIL9tR2cN3vztcLBo47AqFUgHgIA=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201074627-babf9f2cc955 h1:uhQUyDqilPUh58BWtIeSAupjovs1QQjC6pEoErqD86o=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201074627-babf9f2cc955/go.mod h1:lUH49SRidDcQGyXPIL9tR2cN3vztcLBo47AqFUgHgIA=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211207185736-224e4f70c5ad h1:HR3vqf1DS7hEQ0j77J4ctumZgzDIHNXZtag60U9OOig=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211207185736-224e4f70c5ad/go.mod h1:lUH49SRidDcQGyXPIL9tR2cN3vztcLBo47AqFUgHgIA=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211217193303-c005cce171ac h1:EcXyrTUaQJYiHtLQstXdW04sRH9HwH9mpaxy9Lkcomc=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211217193303-c005cce171ac/go.mod h1:lUH49SRidDcQGyXPIL9tR2cN3vztcLBo47AqFUgHgIA=
|
||||
gopkg.in/macaroon-bakery.v2 v2.0.1/go.mod h1:B4/T17l+ZWGwxFSZQmlBwp25x+og7OkhETfr3S9MbIA=
|
||||
gopkg.in/macaroon.v2 v2.0.0/go.mod h1:+I6LnTMkm/uV5ew/0nsulNjL16SK4+C8yDmRUzHR17I=
|
||||
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA=
|
||||
@@ -748,8 +722,8 @@ gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkep
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 h1:yiW+nvdHb9LVqSHQBXfZCieqV4fzYhNBql77zY0ykqs=
|
||||
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637/go.mod h1:BHsqpu/nsuzkT5BpiH1EMZPLyqSMM8JbIavyFACoFNk=
|
||||
gopkg.in/tucnak/telebot.v2 v2.4.1 h1:bUOFHtHhuhPekjHGe1Q1BmITvtBLdQI4yjSMC405KcU=
|
||||
gopkg.in/tucnak/telebot.v2 v2.4.1/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
|
||||
gopkg.in/tucnak/telebot.v2 v2.3.5 h1:TdMJTlG8kvepsvZdy/gPeYEBdwKdwFFjH1AQTua9BOU=
|
||||
gopkg.in/tucnak/telebot.v2 v2.3.5/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
|
||||
gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI=
|
||||
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
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)
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -22,7 +22,6 @@ 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 {
|
||||
@@ -31,7 +30,6 @@ type TelegramConfiguration struct {
|
||||
}
|
||||
type DatabaseConfiguration struct {
|
||||
DbPath string `yaml:"db_path"`
|
||||
ShopBuntDbPath string `yaml:"shop_buntdb_path"`
|
||||
BuntDbPath string `yaml:"buntdb_path"`
|
||||
TransactionsPath string `yaml:"transactions_path"`
|
||||
}
|
||||
|
||||
@@ -9,51 +9,15 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func MigrateAnonIdInt32Hash(db *gorm.DB) error {
|
||||
func MigrateAnonIdHash(db *gorm.DB) error {
|
||||
users := []lnbits.User{}
|
||||
_ = db.Find(&users)
|
||||
for _, u := range users {
|
||||
log.Infof("[MigrateAnonIdInt32Hash] %d -> %d", u.ID, str.Int32Hash(u.ID))
|
||||
log.Info(u.ID, str.Int32Hash(u.ID))
|
||||
u.AnonID = fmt.Sprint(str.Int32Hash(u.ID))
|
||||
tx := db.Save(u)
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[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)
|
||||
errmsg := fmt.Sprintf("[MigrateAnonIdHash] Error: Couldn't migrate user %s (%d)", u.Telegram.Username, u.Telegram.ID)
|
||||
log.Errorln(errmsg)
|
||||
return tx.Error
|
||||
}
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
package errors
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
import "encoding/json"
|
||||
|
||||
type TipBotErrorType int
|
||||
|
||||
const (
|
||||
DecodeAmountError TipBotErrorType = 1000 + iota
|
||||
DecodePerUserAmountError
|
||||
InvalidAmountError
|
||||
InvalidAmountPerUserError
|
||||
GetBalanceError
|
||||
BalanceToLowError
|
||||
)
|
||||
|
||||
func Create(code TipBotErrorType) TipBotError {
|
||||
return errMap[code]
|
||||
}
|
||||
func New(code TipBotErrorType, err error) TipBotError {
|
||||
if err != nil {
|
||||
return TipBotError{Err: err, Message: err.Error(), Code: code}
|
||||
}
|
||||
return Create(code)
|
||||
return TipBotError{Err: err, Message: err.Error(), Code: code}
|
||||
}
|
||||
|
||||
type TipBotError struct {
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
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")}
|
||||
)
|
||||
@@ -25,7 +25,6 @@ func RegisterLanguages() *i18n.Bundle {
|
||||
bundle.LoadMessageFile("translations/pt-br.toml")
|
||||
bundle.LoadMessageFile("translations/tr.toml")
|
||||
bundle.LoadMessageFile("translations/id.toml")
|
||||
bundle.LoadMessageFile("translations/ru.toml")
|
||||
return bundle
|
||||
}
|
||||
func Translate(languageCode string, MessgeID string) string {
|
||||
|
||||
@@ -2,7 +2,6 @@ package lnbits
|
||||
|
||||
import (
|
||||
"github.com/imroc/req"
|
||||
"time"
|
||||
)
|
||||
|
||||
// NewClient returns a new lnbits api client. Pass your API key and url here.
|
||||
@@ -106,6 +105,30 @@ func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx BitInvoice, err e
|
||||
return
|
||||
}
|
||||
|
||||
// Info returns wallet information
|
||||
func (c Client) Payments(w Wallet) (wtx Payments, err error) {
|
||||
// custom header with invoice key
|
||||
invoiceHeader := req.Header{
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"X-Api-Key": w.Inkey,
|
||||
}
|
||||
resp, err := req.Get(c.url+"/api/v1/payments", invoiceHeader, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if resp.Response().StatusCode >= 300 {
|
||||
var reqErr Error
|
||||
resp.ToJSON(&reqErr)
|
||||
err = reqErr
|
||||
return
|
||||
}
|
||||
|
||||
err = resp.ToJSON(&wtx)
|
||||
return
|
||||
}
|
||||
|
||||
// Info returns wallet information
|
||||
func (c Client) Info(w Wallet) (wtx Wallet, err error) {
|
||||
// custom header with invoice key
|
||||
@@ -156,9 +179,7 @@ func (w Wallet) Pay(params PaymentParams, c *Client) (wtx BitInvoice, err error)
|
||||
"Accept": "application/json",
|
||||
"X-Api-Key": w.Adminkey,
|
||||
}
|
||||
r := req.New()
|
||||
r.SetTimeout(time.Hour * 24)
|
||||
resp, err := r.Post(c.url+"/api/v1/payments", adminHeader, req.BodyJSON(¶ms))
|
||||
resp, err := req.Post(c.url+"/api/v1/payments", adminHeader, req.BodyJSON(¶ms))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
+26
-54
@@ -1,15 +1,10 @@
|
||||
package lnbits
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/btcsuite/btcd/btcec"
|
||||
|
||||
"github.com/imroc/req"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
@@ -20,19 +15,16 @@ 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 `json:"anon_id"`
|
||||
AnonIDSha256 string `json:"anon_id_sha256"`
|
||||
UUID string `json:"uuid"`
|
||||
Banned bool `json:"banned"`
|
||||
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"`
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -42,15 +34,6 @@ const (
|
||||
UserStateConfirmLNURLPay
|
||||
UserEnterAmount
|
||||
UserHasEnteredAmount
|
||||
UserEnterUser
|
||||
UserHasEnteredUser
|
||||
UserEnterShopTitle
|
||||
UserStateShopItemSendPhoto
|
||||
UserStateShopItemSendTitle
|
||||
UserStateShopItemSendDescription
|
||||
UserStateShopItemSendPrice
|
||||
UserStateShopItemSendItemFile
|
||||
UserEnterShopsDescription
|
||||
)
|
||||
|
||||
type UserStateKey int
|
||||
@@ -110,30 +93,19 @@ type BitInvoice struct {
|
||||
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
|
||||
type Payments []struct {
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending bool `json:"pending"`
|
||||
Amount int `json:"amount"`
|
||||
Fee int `json:"fee"`
|
||||
Memo string `json:"memo"`
|
||||
Time int `json:"time"`
|
||||
Bolt11 string `json:"bolt11"`
|
||||
Preimage string `json:"preimage"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Extra struct {
|
||||
} `json:"extra"`
|
||||
WalletID string `json:"wallet_id"`
|
||||
Webhook interface{} `json:"webhook"`
|
||||
WebhookStatus interface{} `json:"webhook_status"`
|
||||
}
|
||||
|
||||
@@ -3,25 +3,29 @@ package webhook
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"net/http"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
)
|
||||
|
||||
const (
|
||||
// invoiceReceivedMessage = "⚡️ You received %d sat."
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
httpServer *http.Server
|
||||
bot *tb.Bot
|
||||
@@ -31,16 +35,17 @@ type Server struct {
|
||||
}
|
||||
|
||||
type Webhook struct {
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending bool `json:"pending"`
|
||||
Amount int64 `json:"amount"`
|
||||
Fee int64 `json:"fee"`
|
||||
Memo string `json:"memo"`
|
||||
Time int64 `json:"time"`
|
||||
Bolt11 string `json:"bolt11"`
|
||||
Preimage string `json:"preimage"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Extra struct{} `json:"extra"`
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending int `json:"pending"`
|
||||
Amount int `json:"amount"`
|
||||
Fee int `json:"fee"`
|
||||
Memo string `json:"memo"`
|
||||
Time int `json:"time"`
|
||||
Bolt11 string `json:"bolt11"`
|
||||
Preimage string `json:"preimage"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Extra struct {
|
||||
} `json:"extra"`
|
||||
WalletID string `json:"wallet_id"`
|
||||
Webhook string `json:"webhook"`
|
||||
WebhookStatus interface{} `json:"webhook_status"`
|
||||
@@ -48,7 +53,8 @@ type Webhook struct {
|
||||
|
||||
func NewServer(bot *telegram.TipBot) *Server {
|
||||
srv := &http.Server{
|
||||
Addr: internal.Configuration.Lnbits.WebhookServerUrl.Host,
|
||||
Addr: internal.Configuration.Lnbits.WebhookServerUrl.Host,
|
||||
// Good practice: enforce timeouts for servers you create!
|
||||
WriteTimeout: 15 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
}
|
||||
@@ -80,43 +86,38 @@ func (w *Server) newRouter() *mux.Router {
|
||||
return router
|
||||
}
|
||||
|
||||
func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
log.Debugln("[Webhook] Received request")
|
||||
webhookEvent := Webhook{}
|
||||
func (w Server) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
depositEvent := Webhook{}
|
||||
// need to delete the header otherwise the Decode will fail
|
||||
request.Header.Del("content-length")
|
||||
err := json.NewDecoder(request.Body).Decode(&webhookEvent)
|
||||
err := json.NewDecoder(request.Body).Decode(&depositEvent)
|
||||
if err != nil {
|
||||
log.Errorf("[Webhook] Error decoding request: %s", err.Error())
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
user, err := w.GetUserByWalletId(webhookEvent.WalletID)
|
||||
user, err := w.GetUserByWalletId(depositEvent.WalletID)
|
||||
if err != nil {
|
||||
log.Errorf("[Webhook] Error getting user: %s", err.Error())
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
log.Infoln(fmt.Sprintf("[⚡️ WebHook] User %s (%d) received invoice of %d sat.", telegram.GetUserStr(user.Telegram), user.Telegram.ID, webhookEvent.Amount/1000))
|
||||
log.Infoln(fmt.Sprintf("[WebHook] User %s (%d) received invoice of %d sat.", user.Telegram.Username, user.Telegram.ID, depositEvent.Amount/1000))
|
||||
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), depositEvent.Amount/1000))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
|
||||
writer.WriteHeader(200)
|
||||
|
||||
// trigger invoice events
|
||||
txInvoiceEvent := &telegram.InvoiceEvent{Invoice: &telegram.Invoice{PaymentHash: webhookEvent.PaymentHash}}
|
||||
err = w.buntdb.Get(txInvoiceEvent)
|
||||
// if this invoice is saved in bunt.db, we load it and display the comment from an LNURL invoice
|
||||
tx := &lnurl.Invoice{PaymentHash: depositEvent.PaymentHash}
|
||||
err = w.buntdb.Get(tx)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
} else {
|
||||
// do something with the event
|
||||
if c := telegram.InvoiceCallback[txInvoiceEvent.Callback]; c != nil {
|
||||
c(txInvoiceEvent)
|
||||
return
|
||||
if len(tx.Comment) > 0 {
|
||||
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(`✉️ %s`, str.MarkdownEscape(tx.Comment)))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fallback: send a message to the user if there is no callback for this invoice
|
||||
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), webhookEvent.Amount/1000))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
writer.WriteHeader(200)
|
||||
}
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
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
|
||||
}
|
||||
+84
-246
@@ -8,68 +8,31 @@ import (
|
||||
"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"
|
||||
"github.com/fiatjaf/go-lnurl"
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
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
|
||||
PaymentRequest string `json:"payment_request"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Amount int64 `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
ToUser *lnbits.User `json:"to_user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Paid bool `json:"paid"`
|
||||
PaidAt time.Time `json:"paid_at"`
|
||||
}
|
||||
|
||||
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 (msg Invoice) Key() string {
|
||||
return fmt.Sprintf("payment-hash:%s", msg.PaymentHash)
|
||||
}
|
||||
|
||||
func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
|
||||
func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
|
||||
var err error
|
||||
var response interface{}
|
||||
username := mux.Vars(request)["username"]
|
||||
@@ -78,301 +41,176 @@ func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
|
||||
} else {
|
||||
stringAmount := request.FormValue("amount")
|
||||
if stringAmount == "" {
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Form value 'amount' is not set"))
|
||||
NotFoundHandler(writer, fmt.Errorf("[serveLNURLpSecond] Form value 'amount' is not set"))
|
||||
return
|
||||
}
|
||||
amount, parseError := strconv.Atoi(stringAmount)
|
||||
if parseError != nil {
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int %v", parseError))
|
||||
NotFoundHandler(writer, fmt.Errorf("[serveLNURLpSecond] Couldn't cast amount to int %v", parseError))
|
||||
return
|
||||
}
|
||||
comment := request.FormValue("comment")
|
||||
if len(comment) > CommentAllowed {
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Comment is too long"))
|
||||
NotFoundHandler(writer, fmt.Errorf("[serveLNURLpSecond] Comment is too long"))
|
||||
return
|
||||
}
|
||||
|
||||
// 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)
|
||||
response, err = w.serveLNURLpSecond(username, int64(amount), comment)
|
||||
}
|
||||
// check if error was returned from first or second handlers
|
||||
if err != nil {
|
||||
// log the error
|
||||
log.Errorf("[LNURL] %v", err.Error())
|
||||
log.Errorf("[LNURL] %v", err)
|
||||
if response != nil {
|
||||
// there is a valid error response
|
||||
err = api.WriteResponse(writer, response)
|
||||
err = writeResponse(writer, response)
|
||||
if err != nil {
|
||||
api.NotFoundHandler(writer, err)
|
||||
NotFoundHandler(writer, err)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
// no error from first or second handler
|
||||
err = api.WriteResponse(writer, response)
|
||||
err = writeResponse(writer, response)
|
||||
if err != nil {
|
||||
api.NotFoundHandler(writer, err)
|
||||
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 Lnurl) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error) {
|
||||
func (w Server) serveLNURLpFirst(username string) (*lnurl.LNURLPayResponse1, error) {
|
||||
log.Infof("[LNURL] Serving endpoint for user %s", username)
|
||||
callbackURL, err := url.Parse(fmt.Sprintf("%s/%s/%s", w.callbackHostname.String(), Endpoint, username))
|
||||
callbackURL, err := url.Parse(fmt.Sprintf("%s/%s/%s", w.callbackHostname.String(), lnurlEndpoint, username))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
metadata := w.metaData(username)
|
||||
jsonMeta, err := json.Marshal(metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// produce the metadata including the image
|
||||
metadata := w.getMetaDataCached(username)
|
||||
|
||||
return &lnurl.LNURLPayParams{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: api.StatusOk},
|
||||
Tag: PayRequestTag,
|
||||
return &lnurl.LNURLPayResponse1{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: statusOk},
|
||||
Tag: payRequestTag,
|
||||
Callback: callbackURL.String(),
|
||||
MinSendable: MinSendable,
|
||||
CallbackURL: callbackURL, // probably no need to set this here
|
||||
MinSendable: minSendable,
|
||||
MaxSendable: MaxSendable,
|
||||
EncodedMetadata: metadata.Encode(),
|
||||
EncodedMetadata: string(jsonMeta),
|
||||
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 Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment string, payerData lnurl.PayerDataValues) (*lnurl.LNURLPayValues, error) {
|
||||
func (w Server) serveLNURLpSecond(username string, amount int64, comment string) (*lnurl.LNURLPayResponse2, error) {
|
||||
log.Infof("[LNURL] Serving invoice for user %s", username)
|
||||
if amount_msat < MinSendable || amount_msat > MaxSendable {
|
||||
if amount < minSendable || amount > MaxSendable {
|
||||
// amount is not ok
|
||||
return &lnurl.LNURLPayValues{
|
||||
return &lnurl.LNURLPayResponse2{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.StatusError,
|
||||
Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", MinSendable, MinSendable)},
|
||||
Status: statusError,
|
||||
Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", minSendable, MaxSendable)},
|
||||
}, fmt.Errorf("amount out of bounds")
|
||||
}
|
||||
// check comment length
|
||||
if len(comment) > CommentAllowed {
|
||||
return &lnurl.LNURLPayValues{
|
||||
return &lnurl.LNURLPayResponse2{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.StatusError,
|
||||
Status: statusError,
|
||||
Reason: fmt.Sprintf("Comment too long (max: %d characters).", CommentAllowed)},
|
||||
}, fmt.Errorf("comment too long")
|
||||
}
|
||||
user, tx := findUser(w.database, username)
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
if tx.Error != nil {
|
||||
return &lnurl.LNURLPayValues{
|
||||
return &lnurl.LNURLPayResponse2{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.StatusError,
|
||||
Status: statusError,
|
||||
Reason: fmt.Sprintf("Invalid user.")},
|
||||
}, fmt.Errorf("[GetUser] Couldn't fetch user info from database: %v", tx.Error)
|
||||
}
|
||||
if user.Wallet == nil {
|
||||
return &lnurl.LNURLPayValues{
|
||||
return &lnurl.LNURLPayResponse2{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.StatusError,
|
||||
Status: statusError,
|
||||
Reason: fmt.Sprintf("Invalid user.")},
|
||||
}, fmt.Errorf("[serveLNURLpSecond] user %s not found", username)
|
||||
}
|
||||
// user is ok now create invoice
|
||||
// set wallet lnbits client
|
||||
|
||||
var resp *lnurl.LNURLPayValues
|
||||
var resp *lnurl.LNURLPayResponse2
|
||||
|
||||
// the same description_hash needs to be built in the second request
|
||||
metadata := w.getMetaDataCached(username)
|
||||
|
||||
var payerDataByte []byte
|
||||
var err error
|
||||
if payerData.Email != "" || payerData.LightningAddress != "" || payerData.FreeName != "" {
|
||||
payerDataByte, err = json.Marshal(payerData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
payerDataByte = []byte("")
|
||||
}
|
||||
|
||||
descriptionHash, err := w.descriptionHash(metadata, string(payerDataByte))
|
||||
metadata := w.metaData(username)
|
||||
descriptionHash, err := w.descriptionHash(metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Amount: amount_msat / 1000,
|
||||
Amount: amount / 1000,
|
||||
Out: false,
|
||||
DescriptionHash: descriptionHash,
|
||||
Webhook: w.WebhookServer},
|
||||
w.c)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("[serveLNURLpSecond] Couldn't create invoice: %v", err.Error())
|
||||
resp = &lnurl.LNURLPayValues{
|
||||
err = fmt.Errorf("[serveLNURLpSecond] Couldn't create invoice: %v", err)
|
||||
resp = &lnurl.LNURLPayResponse2{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.StatusError,
|
||||
Status: statusError,
|
||||
Reason: "Couldn't create invoice."},
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
invoiceStruct := &telegram.Invoice{
|
||||
PaymentRequest: invoice.PaymentRequest,
|
||||
PaymentHash: invoice.PaymentHash,
|
||||
Amount: amount_msat / 1000,
|
||||
}
|
||||
// save lnurl invoice struct for later use (will hold the comment or other metadata for a notification when paid)
|
||||
// save invoice struct for later use
|
||||
runtime.IgnoreError(w.buntdb.Set(
|
||||
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(
|
||||
telegram.InvoiceEvent{
|
||||
Invoice: invoiceStruct,
|
||||
User: user,
|
||||
Callback: telegram.InvoiceCallbackLNURLPayReceive,
|
||||
ToUser: user,
|
||||
Amount: amount,
|
||||
Comment: comment,
|
||||
PaymentRequest: invoice.PaymentRequest,
|
||||
PaymentHash: invoice.PaymentHash,
|
||||
CreatedAt: time.Now(),
|
||||
}))
|
||||
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: api.StatusOk},
|
||||
return &lnurl.LNURLPayResponse2{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: statusOk},
|
||||
PR: invoice.PaymentRequest,
|
||||
Routes: make([]struct{}, 0),
|
||||
Routes: make([][]lnurl.RouteInfo, 0),
|
||||
SuccessAction: &lnurl.SuccessAction{Message: "Payment received!", Tag: "message"},
|
||||
}, nil
|
||||
|
||||
}
|
||||
|
||||
// descriptionHash is the SHA256 hash of the metadata
|
||||
func (w Lnurl) descriptionHash(metadata lnurl.Metadata, payerData string) (string, error) {
|
||||
var hashString string
|
||||
var hash [32]byte
|
||||
if len(payerData) == 0 {
|
||||
hash = sha256.Sum256([]byte(metadata.Encode()))
|
||||
hashString = hex.EncodeToString(hash[:])
|
||||
} else {
|
||||
hash = sha256.Sum256([]byte(metadata.Encode() + payerData))
|
||||
hashString = hex.EncodeToString(hash[:])
|
||||
func (w Server) descriptionHash(metadata lnurl.Metadata) (string, error) {
|
||||
jsonMeta, err := json.Marshal(metadata)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
hash := sha256.Sum256([]byte(string(jsonMeta)))
|
||||
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 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
|
||||
}
|
||||
}
|
||||
|
||||
func (w Server) metaData(username string) lnurl.Metadata {
|
||||
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 ""
|
||||
{"text/identifier", fmt.Sprintf("%s@%s", username, w.callbackHostname.Hostname())},
|
||||
{"text/plain", fmt.Sprintf("Pay to %s@%s", username, w.callbackHostname.Hostname())}}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
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
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package price
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
@@ -62,7 +63,7 @@ func (p *PriceWatcher) Watch() error {
|
||||
for currency, _ := range p.Currencies {
|
||||
avg_price := 0.0
|
||||
n_responses := 0
|
||||
for _, getPrice := range p.Exchanges {
|
||||
for exchange, getPrice := range p.Exchanges {
|
||||
fprice, err := getPrice(currency)
|
||||
if err != nil {
|
||||
// log.Debug(err)
|
||||
@@ -71,11 +72,11 @@ func (p *PriceWatcher) Watch() error {
|
||||
}
|
||||
n_responses++
|
||||
avg_price += fprice
|
||||
// log.Debugf("[PriceWatcher] %s %s price: %f", exchange, currency, fprice)
|
||||
log.Debugf("[PriceWatcher] %s %s price: %f", exchange, currency, fprice)
|
||||
time.Sleep(time.Second * time.Duration(2))
|
||||
}
|
||||
Price[currency] = avg_price / float64(n_responses)
|
||||
// log.Debugf("[PriceWatcher] Average %s price: %f", currency, Price[currency])
|
||||
log.Debugf("[PriceWatcher] Average %s price: %f", currency, Price[currency])
|
||||
}
|
||||
time.Sleep(p.UpdateInterval)
|
||||
}
|
||||
@@ -84,7 +85,7 @@ func (p *PriceWatcher) Watch() error {
|
||||
func (p *PriceWatcher) GetCoinbasePrice(currency string) (float64, error) {
|
||||
coinbaseEndpoint, err := url.Parse(fmt.Sprintf("https://api.coinbase.com/v2/prices/spot?currency=%s", currency))
|
||||
response, err := p.client.Get(coinbaseEndpoint.String())
|
||||
if err != nil {
|
||||
if err, ok := err.(net.Error); ok && err.Timeout() {
|
||||
return 0, err
|
||||
}
|
||||
bodyBytes, err := ioutil.ReadAll(response.Body)
|
||||
@@ -110,7 +111,7 @@ func (p *PriceWatcher) GetBitfinexPrice(currency string) (float64, error) {
|
||||
pair := bitfinexCurrencyToPair[currency]
|
||||
bitfinexEndpoint, err := url.Parse(fmt.Sprintf("https://api.bitfinex.com/v1/pubticker/%s", pair))
|
||||
response, err := p.client.Get(bitfinexEndpoint.String())
|
||||
if err != nil {
|
||||
if err, ok := err.(net.Error); ok && err.Timeout() {
|
||||
return 0, err
|
||||
}
|
||||
bodyBytes, err := ioutil.ReadAll(response.Body)
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
package rate
|
||||
|
||||
import (
|
||||
"context"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"golang.org/x/time/rate"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
// Limiter
|
||||
type Limiter struct {
|
||||
keys map[string]*rate.Limiter
|
||||
mu *sync.RWMutex
|
||||
r rate.Limit
|
||||
b int
|
||||
}
|
||||
|
||||
var idLimiter *Limiter
|
||||
var globalLimiter *rate.Limiter
|
||||
|
||||
// NewLimiter creates both chat and global rate limiters.
|
||||
func Start() {
|
||||
idLimiter = newIdRateLimiter(rate.Limit(0.29), 19)
|
||||
globalLimiter = rate.NewLimiter(rate.Limit(30), 30)
|
||||
}
|
||||
|
||||
// NewRateLimiter .
|
||||
func newIdRateLimiter(r rate.Limit, b int) *Limiter {
|
||||
i := &Limiter{
|
||||
keys: make(map[string]*rate.Limiter),
|
||||
mu: &sync.RWMutex{},
|
||||
r: r,
|
||||
b: b,
|
||||
}
|
||||
|
||||
return i
|
||||
}
|
||||
|
||||
func CheckLimit(to interface{}) {
|
||||
globalLimiter.Wait(context.Background())
|
||||
var id string
|
||||
switch to.(type) {
|
||||
case string:
|
||||
id = to.(string)
|
||||
case *tb.Chat:
|
||||
id = strconv.FormatInt(to.(*tb.Chat).ID, 10)
|
||||
case *tb.User:
|
||||
id = strconv.FormatInt(to.(*tb.User).ID, 10)
|
||||
case tb.Recipient:
|
||||
id = to.(tb.Recipient).Recipient()
|
||||
case *tb.Message:
|
||||
if to.(*tb.Message).Chat != nil {
|
||||
id = strconv.FormatInt(to.(*tb.Message).Chat.ID, 10)
|
||||
}
|
||||
}
|
||||
if len(id) > 0 {
|
||||
log.Tracef("[Check Limit] limiter for %+v", id)
|
||||
idLimiter.GetLimiter(id).Wait(context.Background())
|
||||
return
|
||||
}
|
||||
log.Tracef("[Check Limit] skipping id limiter for %+v", to)
|
||||
}
|
||||
|
||||
// Add creates a new rate limiter and adds it to the keys map,
|
||||
// using the key
|
||||
func (i *Limiter) Add(key string) *rate.Limiter {
|
||||
i.mu.Lock()
|
||||
defer i.mu.Unlock()
|
||||
|
||||
limiter := rate.NewLimiter(i.r, i.b)
|
||||
|
||||
i.keys[key] = limiter
|
||||
|
||||
return limiter
|
||||
}
|
||||
|
||||
// GetLimiter returns the rate limiter for the provided key if it exists.
|
||||
// Otherwise, calls Add to add key address to the map
|
||||
func (i *Limiter) GetLimiter(key string) *rate.Limiter {
|
||||
i.mu.Lock()
|
||||
limiter, exists := i.keys[key]
|
||||
|
||||
if !exists {
|
||||
i.mu.Unlock()
|
||||
return i.Add(key)
|
||||
}
|
||||
|
||||
i.mu.Unlock()
|
||||
|
||||
return limiter
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
"time"
|
||||
)
|
||||
|
||||
var tickerMap cmap.ConcurrentMap
|
||||
|
||||
func init() {
|
||||
tickerMap = cmap.New()
|
||||
}
|
||||
|
||||
var defaultTickerCoolDown = time.Second * 10
|
||||
|
||||
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
|
||||
type ResettableFunctionTicker struct {
|
||||
Ticker *time.Ticker
|
||||
ResetChan chan struct{} // channel used to reset the ticker
|
||||
duration time.Duration
|
||||
Started bool
|
||||
name string
|
||||
}
|
||||
type ResettableFunctionTickerOption func(*ResettableFunctionTicker)
|
||||
|
||||
func WithDuration(d time.Duration) ResettableFunctionTickerOption {
|
||||
return func(a *ResettableFunctionTicker) {
|
||||
a.duration = d
|
||||
}
|
||||
}
|
||||
func RemoveTicker(name string) {
|
||||
tickerMap.Remove(name)
|
||||
}
|
||||
func GetTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
|
||||
|
||||
if t, ok := tickerMap.Get(name); ok {
|
||||
return t.(*ResettableFunctionTicker)
|
||||
} else {
|
||||
t := NewResettableFunctionTicker(name, option...)
|
||||
tickerMap.Set(name, t)
|
||||
return t
|
||||
}
|
||||
}
|
||||
func NewResettableFunctionTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
|
||||
t := &ResettableFunctionTicker{
|
||||
ResetChan: make(chan struct{}, 1),
|
||||
name: name,
|
||||
}
|
||||
|
||||
for _, opt := range option {
|
||||
opt(t)
|
||||
}
|
||||
if t.duration == 0 {
|
||||
t.duration = defaultTickerCoolDown
|
||||
}
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *ResettableFunctionTicker) Do(f func()) {
|
||||
t.Started = true
|
||||
tickerMap.Set(t.name, t)
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-t.Ticker.C:
|
||||
// ticker delivered signal. do function f
|
||||
f()
|
||||
return
|
||||
case <-t.ResetChan:
|
||||
// reset signal received. creating new ticker.
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
package mutex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"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/{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 mutex %s.\nCurrent number of locks: %d\nLocks: %+v",
|
||||
vars["id"], len(mutexMap.Keys()), mutexMap.Keys())))
|
||||
return
|
||||
}
|
||||
w.Write([]byte(fmt.Sprintf("Mutex %s not found!", vars["id"])))
|
||||
}
|
||||
|
||||
// checkSoftLock checks in mutexMap how often an existing mutex was already SoftLocked.
|
||||
// The counter is there to avoid multiple recursive locking of an object in the mutexMap.
|
||||
// This happens if multiple handlers call each other and try to lock/unlock multiple times
|
||||
// the same mutex.
|
||||
func checkSoftLock(s string) int {
|
||||
if v, ok := mutexMap.Get(fmt.Sprintf("nLocks:%s", s)); ok {
|
||||
return v.(int)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// LockWithContext locks a mutex only if it hasn't been locked before in a context.
|
||||
// LockWithContext should be used to lock objects like faucets etc.
|
||||
// The context carries a uid that is unique the each request (message, button press, etc.).
|
||||
// If the uid has a lock already *for a certain object*, it increments the
|
||||
// nLocks in the mutexMap. If not, it locks the object. This is supposed to lock only if nLock == 0.
|
||||
func LockWithContext(ctx context.Context, s string) {
|
||||
uid := ctx.Value("uid").(string)
|
||||
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))
|
||||
var nLocks = checkSoftLock(uid)
|
||||
if nLocks == 0 {
|
||||
Lock(s)
|
||||
} else {
|
||||
log.Tracef("[Mutex] Skip lock (nLocks: %d)", nLocks)
|
||||
}
|
||||
nLocks++
|
||||
mutexMap.Set(fmt.Sprintf("nLocks:%s", uid), nLocks)
|
||||
Unlock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
|
||||
}
|
||||
|
||||
// UnlockWithContext unlock a mutex only if it has been locked once within a context.
|
||||
// If it has been locked more than once
|
||||
// it only decrements nLocks and skips the unlock of the mutex. This is supposed to unlock only for
|
||||
// nLocks == 1
|
||||
func UnlockWithContext(ctx context.Context, s string) {
|
||||
uid := ctx.Value("uid").(string)
|
||||
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--
|
||||
mutexMap.Set(fmt.Sprintf("nLocks:%s", uid), nLocks)
|
||||
if nLocks == 0 {
|
||||
Unlock(s)
|
||||
mutexMap.Remove(fmt.Sprintf("nLocks:%s", uid))
|
||||
} else {
|
||||
log.Tracef("[Mutex] Skip unlock (nLocks: %d)", nLocks)
|
||||
}
|
||||
Unlock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
|
||||
//mutexMap.Remove(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
|
||||
}
|
||||
|
||||
// Lock locks a mutex in the mutexMap. If the mutex is already in the map, it locks the current call.
|
||||
// After it another call unlocks the mutex (and deletes it from the mutexMap) the mutex written again into the mutexMap.
|
||||
// If the mutex was not in the mutexMap before, a new mutext is created and locked and written into the mutexMap.
|
||||
func Lock(s string) {
|
||||
log.Tracef("[Mutex] Attempt Lock %s", s)
|
||||
if m, ok := mutexMap.Get(s); ok {
|
||||
m.(*sync.Mutex).Lock()
|
||||
// write into mutex map
|
||||
mutexMapSync.Lock()
|
||||
mutexMap.Set(s, m)
|
||||
mutexMapSync.Unlock()
|
||||
} else {
|
||||
m := &sync.Mutex{}
|
||||
m.Lock()
|
||||
// write into mutex map
|
||||
mutexMapSync.Lock()
|
||||
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)
|
||||
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)
|
||||
}
|
||||
mutexMapSync.Unlock()
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package once
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var onceMap cmap.ConcurrentMap
|
||||
|
||||
func init() {
|
||||
onceMap = cmap.New()
|
||||
}
|
||||
|
||||
func New(objectKey string) {
|
||||
onceMap.Set(objectKey, cmap.New())
|
||||
}
|
||||
|
||||
// Once creates a map of keys k1 with a map of keys k2.
|
||||
// The idea is that an object with ID k1 can create a list of users k2
|
||||
// that have already interacted with the object. If the user k2 is in the list,
|
||||
// the object is not allowed to accessed again.
|
||||
func Once(k1, k2 string) error {
|
||||
i, ok := onceMap.Get(k1)
|
||||
if ok {
|
||||
return setOrReturn(i.(cmap.ConcurrentMap), k2)
|
||||
}
|
||||
userMap := cmap.New()
|
||||
onceMap.Set(k1, userMap)
|
||||
log.Tracef("[Once] Added key %s to onceMap (len=%d)", k1, len(onceMap.Keys()))
|
||||
return setOrReturn(userMap, k2)
|
||||
}
|
||||
|
||||
// setOrReturn sets the key k2 in the map i if it is not already set.
|
||||
func setOrReturn(objectMap cmap.ConcurrentMap, k2 string) error {
|
||||
if _, ok := objectMap.Get(k2); ok {
|
||||
return fmt.Errorf("[Once] %s already consumed object", k2)
|
||||
}
|
||||
objectMap.Set(k2, true)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove removes the key k1 from the map. Should be called after Once was called and
|
||||
// the object k1 finished.
|
||||
func Remove(k1 string) {
|
||||
onceMap.Remove(k1)
|
||||
log.Tracef("[Once] Removed key %s from onceMap (len=%d)", k1, len(onceMap.Keys()))
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"time"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
gocache "github.com/patrickmn/go-cache"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var transactionCache = store.NewGoCache(gocache.New(5*time.Minute, 10*time.Minute), nil)
|
||||
|
||||
type Base struct {
|
||||
ID string `json:"id"`
|
||||
Active bool `json:"active"`
|
||||
Canceled bool `json:"canceled"`
|
||||
CreatedAt time.Time `json:"created"`
|
||||
UpdatedAt time.Time `json:"updated"`
|
||||
}
|
||||
|
||||
type Option func(b *Base)
|
||||
|
||||
func ID(id string) Option {
|
||||
return func(btx *Base) {
|
||||
btx.ID = id
|
||||
}
|
||||
}
|
||||
|
||||
func New(opts ...Option) *Base {
|
||||
btx := &Base{
|
||||
Active: true,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(btx)
|
||||
}
|
||||
return btx
|
||||
}
|
||||
|
||||
func (tx Base) Key() string {
|
||||
return tx.ID
|
||||
}
|
||||
|
||||
func (tx *Base) Inactivate(s Storable, db *DB) error {
|
||||
tx.Active = false
|
||||
err := tx.Set(s, db)
|
||||
if err != nil {
|
||||
log.Tracef("[Bunt Inactivate] %s Error: %s", tx.ID, err.Error())
|
||||
return err
|
||||
}
|
||||
log.Tracef("[Bunt Inactivate] %s", tx.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tx *Base) Get(s Storable, db *DB) (Storable, error) {
|
||||
cacheTx, err := transactionCache.Get(s.Key())
|
||||
if err != nil {
|
||||
err := db.Get(s)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
log.Tracef("[Bunt] get object %s", s.Key())
|
||||
return s, transactionCache.Set(s.Key(), s, &store.Options{Expiration: 5 * time.Minute})
|
||||
}
|
||||
log.Tracef("[Bunt Cache] get object %s", s.Key())
|
||||
return cacheTx.(Storable), err
|
||||
|
||||
}
|
||||
|
||||
func (tx *Base) Set(s Storable, db *DB) error {
|
||||
tx.UpdatedAt = time.Now()
|
||||
err := db.Set(s)
|
||||
if err != nil {
|
||||
log.Errorf("[Bunt] could not set object: %v", err.Error())
|
||||
return err
|
||||
}
|
||||
log.Tracef("[Bunt] set object %s", s.Key())
|
||||
err = transactionCache.Set(s.Key(), s, &store.Options{Expiration: 5 * time.Minute})
|
||||
if err != nil {
|
||||
log.Errorf("[Bunt Cache] could not set object: %v", err.Error())
|
||||
}
|
||||
log.Tracef("[Bunt Cache] set object: %s", s.Key())
|
||||
return err
|
||||
}
|
||||
|
||||
func (tx *Base) Delete(s Storable, db *DB) error {
|
||||
tx.UpdatedAt = time.Now()
|
||||
runtime.IgnoreError(transactionCache.Delete(s.Key()))
|
||||
return db.Delete(s.Key(), s)
|
||||
}
|
||||
+15
-23
@@ -2,7 +2,7 @@ package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/buntdb"
|
||||
)
|
||||
@@ -78,31 +78,23 @@ func (db *DB) Set(object Storable) error {
|
||||
}
|
||||
|
||||
// Delete a storable item.
|
||||
// todo -- not ascend users index
|
||||
func (db *DB) Delete(index string, object Storable) error {
|
||||
return db.Update(func(tx *buntdb.Tx) error {
|
||||
_, err := tx.Get(object.Key())
|
||||
if err != nil {
|
||||
return err
|
||||
var delkeys []string
|
||||
runtime.IgnoreError(
|
||||
tx.Ascend(index, func(key, value string) bool {
|
||||
if key == object.Key() {
|
||||
delkeys = append(delkeys, key)
|
||||
}
|
||||
return true
|
||||
}),
|
||||
)
|
||||
for _, k := range delkeys {
|
||||
if _, err := tx.Delete(k); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := tx.Delete(object.Key()); err != nil {
|
||||
return err
|
||||
}
|
||||
// OLD: from gohumble:
|
||||
// todo -- not ascend users index
|
||||
// var delkeys []string
|
||||
// runtime.IgnoreError(
|
||||
// tx.Ascend(index, func(key, value string) bool {
|
||||
// if key == object.Key() {
|
||||
// delkeys = append(delkeys, key)
|
||||
// }
|
||||
// return true
|
||||
// }),
|
||||
// )
|
||||
// for _, k := range delkeys {
|
||||
// if _, err := tx.Delete(k); err != nil {
|
||||
// return err
|
||||
// }
|
||||
// }
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package transaction
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
)
|
||||
|
||||
type Base struct {
|
||||
ID string `json:"id"`
|
||||
Active bool `json:"active"`
|
||||
InTransaction bool `json:"intransaction"`
|
||||
CreatedAt time.Time `json:"created"`
|
||||
UpdatedAt time.Time `json:"updated"`
|
||||
MessageID string `json:"messageid"`
|
||||
ChatID string `json:"chatid"`
|
||||
MessageURL string `json:"messageurl"`
|
||||
}
|
||||
|
||||
type Option func(b *Base)
|
||||
|
||||
func ID(id string) Option {
|
||||
return func(btx *Base) {
|
||||
btx.ID = id
|
||||
}
|
||||
}
|
||||
|
||||
func New(opts ...Option) *Base {
|
||||
btx := &Base{
|
||||
Active: true,
|
||||
InTransaction: false,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(btx)
|
||||
}
|
||||
return btx
|
||||
}
|
||||
|
||||
func (tx Base) Key() string {
|
||||
return tx.ID
|
||||
}
|
||||
func (tx *Base) Lock(s storage.Storable, db *storage.DB) error {
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
tx.InTransaction = true
|
||||
err := tx.Set(s, db)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tx *Base) Release(s storage.Storable, db *storage.DB) error {
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
tx.InTransaction = false
|
||||
err := tx.Set(s, db)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tx *Base) Inactivate(s storage.Storable, db *storage.DB) error {
|
||||
tx.Active = false
|
||||
err := tx.Set(s, db)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tx *Base) Get(s storage.Storable, db *storage.DB) (storage.Storable, error) {
|
||||
err := db.Get(s)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
// to avoid race conditions, we block the call if there is
|
||||
// already an active transaction by loop until InTransaction is false
|
||||
ticker := time.NewTicker(time.Second * 10)
|
||||
for tx.InTransaction {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
return nil, fmt.Errorf("transaction timeout")
|
||||
default:
|
||||
time.Sleep(time.Duration(500) * time.Millisecond)
|
||||
err = db.Get(s)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not get transaction")
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (tx *Base) Set(s storage.Storable, db *storage.DB) error {
|
||||
tx.UpdatedAt = time.Now()
|
||||
return db.Set(s)
|
||||
}
|
||||
@@ -1,12 +1,9 @@
|
||||
package str
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
)
|
||||
|
||||
var markdownV2Escapes = []string{"_", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!"}
|
||||
@@ -41,17 +38,3 @@ func Int64Hash(s string) uint64 {
|
||||
h.Write([]byte(s))
|
||||
return h.Sum64()
|
||||
}
|
||||
|
||||
func AnonIdSha256(u *lnbits.User) string {
|
||||
h := sha256.Sum256([]byte(u.Wallet.ID))
|
||||
hash := fmt.Sprintf("%x", h)
|
||||
anon_id := fmt.Sprintf("0x%s", hash[:16]) // starts with 0x because that can't be a valid telegram username
|
||||
return anon_id
|
||||
}
|
||||
|
||||
func UUIDSha256(u *lnbits.User) string {
|
||||
h := sha256.Sum256([]byte(u.Wallet.ID))
|
||||
hash := fmt.Sprintf("%x", h)
|
||||
anon_id := fmt.Sprintf("1x%s", hash[len(hash)-16:]) // starts with 1x because that can't be a valid telegram username
|
||||
return anon_id
|
||||
}
|
||||
|
||||
@@ -3,48 +3,45 @@ 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"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/price"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func getArgumentFromCommand(input string, which int) (output string, err error) {
|
||||
if len(strings.Split(input, " ")) < which+1 {
|
||||
return "", fmt.Errorf("message doesn't contain enough arguments")
|
||||
return "", errors.New("message doesn't contain enough arguments")
|
||||
}
|
||||
output = strings.Split(input, " ")[which]
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func decodeAmountFromCommand(input string) (amount int64, err error) {
|
||||
func decodeAmountFromCommand(input string) (amount int, err error) {
|
||||
if len(strings.Split(input, " ")) < 2 {
|
||||
errmsg := "message doesn't contain any amount"
|
||||
// log.Errorln(errmsg)
|
||||
return 0, fmt.Errorf(errmsg)
|
||||
return 0, errors.New(errmsg)
|
||||
}
|
||||
amount, err = getAmount(strings.Split(input, " ")[1])
|
||||
return amount, err
|
||||
}
|
||||
|
||||
func getAmount(input string) (amount int64, err error) {
|
||||
func getAmount(input string) (amount int, err error) {
|
||||
// convert something like 1.2k into 1200
|
||||
if strings.HasSuffix(strings.ToLower(input), "k") {
|
||||
fmount, err := strconv.ParseFloat(strings.TrimSpace(input[:len(input)-1]), 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
amount = int64(fmount * 1000)
|
||||
amount = int(fmount * 1000)
|
||||
return amount, err
|
||||
}
|
||||
|
||||
@@ -62,20 +59,20 @@ func getAmount(input string) (amount int64, err error) {
|
||||
return 0, err
|
||||
}
|
||||
if !(price.Price[currency] > 0) {
|
||||
return 0, fmt.Errorf("price is zero")
|
||||
return 0, errors.New("price is zero")
|
||||
}
|
||||
amount = int64(fmount / price.Price[currency] * float64(100_000_000))
|
||||
amount = int(fmount / price.Price[currency] * float64(100_000_000))
|
||||
return amount, nil
|
||||
}
|
||||
}
|
||||
|
||||
// use plain integer as satoshis
|
||||
amount, err = strconv.ParseInt(input, 10, 64)
|
||||
amount, err = strconv.Atoi(input)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if amount <= 0 {
|
||||
return 0, fmt.Errorf("amount must be greater than 0")
|
||||
return 0, errors.New("amount must be greater than 0")
|
||||
}
|
||||
return amount, err
|
||||
}
|
||||
@@ -101,16 +98,16 @@ func (bot *TipBot) askForAmount(ctx context.Context, id string, eventType string
|
||||
AmountMax: amountMax,
|
||||
OiringalCommand: originalCommand,
|
||||
}
|
||||
// set LNURLPayParams in the state of the user
|
||||
// set LNURLPayResponse1 in the state of the user
|
||||
stateDataJson, err := json.Marshal(enterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserEnterAmount, string(stateDataJson))
|
||||
askAmountText := Translate(ctx, "enterAmountMessage")
|
||||
askAmountText := Translate(ctx, "lnurlEnterAmountMessage")
|
||||
if amountMin > 0 && amountMax >= amountMin {
|
||||
askAmountText = fmt.Sprintf(Translate(ctx, "enterAmountRangeMessage"), enterAmountStateData.AmountMin/1000, enterAmountStateData.AmountMax/1000)
|
||||
askAmountText = fmt.Sprintf(Translate(ctx, "lnurlEnterAmountRangeMessage"), enterAmountStateData.AmountMin/1000, enterAmountStateData.AmountMax/1000)
|
||||
}
|
||||
// Let the user enter an amount and return
|
||||
bot.trySendMessage(user.Telegram, askAmountText, tb.ForceReply)
|
||||
@@ -120,15 +117,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) (context.Context, error) {
|
||||
func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return // errors.New("user has no wallet"), 0
|
||||
}
|
||||
|
||||
if !(user.StateKey == lnbits.UserEnterAmount) {
|
||||
ResetUserState(user, bot)
|
||||
return ctx, fmt.Errorf("invalid statekey")
|
||||
return // errors.New("user state does not match"), 0
|
||||
}
|
||||
|
||||
var EnterAmountStateData EnterAmountStateData
|
||||
@@ -136,7 +133,7 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) (conte
|
||||
if err != nil {
|
||||
log.Errorf("[enterAmountHandler] %s", err.Error())
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
amount, err := getAmount(m.Text)
|
||||
@@ -144,28 +141,26 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) (conte
|
||||
log.Warnf("[enterAmountHandler] %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
return //err, 0
|
||||
}
|
||||
// amount not in allowed range from LNURL
|
||||
if EnterAmountStateData.AmountMin > 0 && EnterAmountStateData.AmountMax >= EnterAmountStateData.AmountMin && // this line checks whether min_max is set at all
|
||||
(amount > int64(EnterAmountStateData.AmountMax/1000) || amount < int64(EnterAmountStateData.AmountMin/1000)) { // this line then checks whether the amount is in the range
|
||||
(amount > int(EnterAmountStateData.AmountMax/1000) || amount < int(EnterAmountStateData.AmountMin/1000)) { // this line then checks whether the amount is in the range
|
||||
err = fmt.Errorf("amount not in range")
|
||||
log.Warnf("[enterAmountHandler] %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), EnterAmountStateData.AmountMin/1000, EnterAmountStateData.AmountMax/1000))
|
||||
ResetUserState(user, bot)
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
return
|
||||
}
|
||||
|
||||
// find out which type the object in bunt has waiting for an amount
|
||||
// we stored this in the EnterAmountStateData before
|
||||
switch EnterAmountStateData.Type {
|
||||
case "LnurlPayState":
|
||||
tx := &LnurlPayState{Base: storage.New(storage.ID(EnterAmountStateData.ID))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
tx := &LnurlPayState{Base: transaction.New(transaction.ID(EnterAmountStateData.ID))}
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
LnurlPayState := sn.(*LnurlPayState)
|
||||
LnurlPayState.Amount = amount * 1000 // mSat
|
||||
@@ -176,49 +171,35 @@ func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) (conte
|
||||
StateDataJson, err := json.Marshal(EnterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
|
||||
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 ctx, err
|
||||
}
|
||||
LnurlWithdrawState := sn.(LnurlWithdrawState)
|
||||
LnurlWithdrawState.Amount = amount * 1000 // mSat
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(LnurlWithdrawState.Set(LnurlWithdrawState, bot.Bunt))
|
||||
|
||||
EnterAmountStateData.Amount = int64(amount) * 1000 // mSat
|
||||
StateDataJson, err := json.Marshal(EnterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
|
||||
return bot.lnurlWithdrawHandlerWithdraw(ctx, m)
|
||||
bot.lnurlPayHandlerSend(ctx, m)
|
||||
return
|
||||
case "CreateInvoiceState":
|
||||
m.Text = fmt.Sprintf("/invoice %d", amount)
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
return bot.invoiceHandler(ctx, m)
|
||||
bot.invoiceHandler(ctx, m)
|
||||
return
|
||||
case "CreateDonationState":
|
||||
m.Text = fmt.Sprintf("/donate %d", amount)
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
return bot.donationHandler(ctx, m)
|
||||
bot.donationHandler(ctx, m)
|
||||
return
|
||||
case "CreateSendState":
|
||||
splits := strings.SplitAfterN(EnterAmountStateData.OiringalCommand, " ", 2)
|
||||
if len(splits) > 1 {
|
||||
m.Text = fmt.Sprintf("/send %d %s", amount, splits[1])
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
return bot.sendHandler(ctx, m)
|
||||
bot.sendHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
return
|
||||
default:
|
||||
ResetUserState(user, bot)
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
return
|
||||
}
|
||||
// // reset database entry
|
||||
// ResetUserState(user, bot)
|
||||
// return
|
||||
}
|
||||
|
||||
@@ -3,19 +3,15 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot *TipBot) balanceHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
func (bot TipBot) balanceHandler(ctx context.Context, m *tb.Message) {
|
||||
// check and print all commands
|
||||
if len(m.Text) > 0 {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
}
|
||||
|
||||
bot.anyTextHandler(ctx, m)
|
||||
// reply only in private message
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
@@ -24,11 +20,12 @@ func (bot *TipBot) balanceHandler(ctx context.Context, m *tb.Message) (context.C
|
||||
// first check whether the user is initialized
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
|
||||
if !user.Initialized {
|
||||
return bot.startHandler(ctx, m)
|
||||
bot.startHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
usrStr := GetUserStr(m.Sender)
|
||||
@@ -36,10 +33,10 @@ func (bot *TipBot) balanceHandler(ctx context.Context, m *tb.Message) (context.C
|
||||
if err != nil {
|
||||
log.Errorf("[/balance] Error fetching %s's balance: %s", usrStr, err)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "balanceErrorMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[/balance] %s's balance: %d sat\n", usrStr, balance)
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "balanceMessage"), balance))
|
||||
return ctx, nil
|
||||
return
|
||||
}
|
||||
|
||||
@@ -2,35 +2,26 @@ 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"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
gocache "github.com/patrickmn/go-cache"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
"gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type TipBot struct {
|
||||
Database *gorm.DB
|
||||
Bunt *storage.DB
|
||||
ShopBunt *storage.DB
|
||||
logger *gorm.DB
|
||||
Telegram *tb.Bot
|
||||
Telegram *telebot.Bot
|
||||
Client *lnbits.Client
|
||||
limiter map[string]limiter.Limiter
|
||||
Cache
|
||||
}
|
||||
type Cache struct {
|
||||
@@ -48,13 +39,11 @@ func NewBot() TipBot {
|
||||
gocacheStore := store.NewGoCache(gocacheClient, nil)
|
||||
// create sqlite databases
|
||||
db, txLogger := AutoMigration()
|
||||
limiter.Start()
|
||||
return TipBot{
|
||||
Database: db,
|
||||
Client: lnbits.NewClient(internal.Configuration.Lnbits.AdminKey, internal.Configuration.Lnbits.Url),
|
||||
logger: txLogger,
|
||||
Bunt: createBunt(internal.Configuration.Database.BuntDbPath),
|
||||
ShopBunt: createBunt(internal.Configuration.Database.ShopBuntDbPath),
|
||||
Bunt: createBunt(),
|
||||
Telegram: newTelegramBot(),
|
||||
Cache: Cache{GoCacheStore: gocacheStore},
|
||||
}
|
||||
@@ -86,62 +75,14 @@ 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() {
|
||||
func (bot TipBot) Start() {
|
||||
log.Infof("[Telegram] Authorized on account @%s", bot.Telegram.Me.Username)
|
||||
// initialize the bot wallet
|
||||
err := bot.initBotWallet()
|
||||
if err != nil {
|
||||
log.Errorf("Could not initialize bot wallet: %s", err.Error())
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
// 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()
|
||||
bot.Telegram.Start()
|
||||
}
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
// we can't use space in the label of buttons, because string splitting will mess everything up.
|
||||
const (
|
||||
MainMenuCommandSend = "💸 Send"
|
||||
MainMenuCommandBalance = "Balance"
|
||||
MainMenuCommandInvoice = "⚡️ Invoice"
|
||||
MainMenuCommandHelp = "📖 Help"
|
||||
SendMenuCommandEnter = "👤 Enter"
|
||||
)
|
||||
|
||||
var (
|
||||
mainMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnHelpMainMenu = mainMenu.Text(MainMenuCommandHelp)
|
||||
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() {
|
||||
mainMenu.Reply(
|
||||
mainMenu.Row(btnBalanceMainMenu, btnHelpMainMenu),
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu),
|
||||
)
|
||||
}
|
||||
|
||||
// buttonWrapper wrap buttons slice in rows of length i
|
||||
func buttonWrapper(buttons []tb.Btn, markup *tb.ReplyMarkup, length int) []tb.Row {
|
||||
buttonLength := len(buttons)
|
||||
rows := make([]tb.Row, 0)
|
||||
|
||||
if buttonLength > length {
|
||||
for i := 0; i < buttonLength; i = i + length {
|
||||
buttonRow := make([]tb.Btn, length)
|
||||
if i+length < buttonLength {
|
||||
buttonRow = buttons[i : i+length]
|
||||
} else {
|
||||
buttonRow = buttons[i:]
|
||||
}
|
||||
rows = append(rows, markup.Row(buttonRow...))
|
||||
}
|
||||
return rows
|
||||
}
|
||||
rows = append(rows, markup.Row(buttons...))
|
||||
return rows
|
||||
}
|
||||
|
||||
// mainMenuBalanceButtonUpdate updates the balance button in the mainMenu
|
||||
func (bot *TipBot) mainMenuBalanceButtonUpdate(to int64) {
|
||||
var user *lnbits.User
|
||||
var err error
|
||||
if user, err = getCachedUser(&tb.User{ID: to}, *bot); err != nil {
|
||||
user, err = GetLnbitsUser(&tb.User{ID: to}, *bot)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
updateCachedUser(user, *bot)
|
||||
}
|
||||
if user.Wallet != nil {
|
||||
amount, err := bot.GetUserBalanceCached(user)
|
||||
if err == nil {
|
||||
log.Tracef("[appendMainMenu] user %s balance %d sat", GetUserStr(user.Telegram), amount)
|
||||
MainMenuCommandBalance := fmt.Sprintf("%s %d sat", MainMenuCommandBalance, amount)
|
||||
btnBalanceMainMenu = mainMenu.Text(MainMenuCommandBalance)
|
||||
mainMenu.Reply(
|
||||
mainMenu.Row(btnBalanceMainMenu),
|
||||
mainMenu.Row(btnInvoiceMainMenu, btnSendMainMenu, btnHelpMainMenu),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (bot *TipBot) appendMainMenu(to int64, recipient interface{}, options []interface{}) []interface{} {
|
||||
|
||||
// update the balance button
|
||||
if to > 0 {
|
||||
bot.mainMenuBalanceButtonUpdate(to)
|
||||
}
|
||||
|
||||
appendKeyboard := true
|
||||
for _, option := range options {
|
||||
if option == tb.ForceReply {
|
||||
appendKeyboard = false
|
||||
}
|
||||
switch option.(type) {
|
||||
case *tb.ReplyMarkup:
|
||||
appendKeyboard = false
|
||||
//option.(*tb.ReplyMarkup).ReplyKeyboard = mainMenu.ReplyKeyboard
|
||||
//if option.(*tb.ReplyMarkup).InlineKeyboard == nil {
|
||||
// options = append(options[:i], options[i+1:]...)
|
||||
//}
|
||||
}
|
||||
}
|
||||
// to > 0 is private chats
|
||||
if to > 0 && appendKeyboard {
|
||||
options = append(options, mainMenu)
|
||||
}
|
||||
return options
|
||||
}
|
||||
@@ -1,20 +1,12 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"os"
|
||||
"github.com/eko/gocache/store"
|
||||
"reflect"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/database"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
@@ -23,7 +15,7 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -33,9 +25,9 @@ const (
|
||||
TipTooltipKeyPattern = "tip-tool-tip:*"
|
||||
)
|
||||
|
||||
func createBunt(file string) *storage.DB {
|
||||
func createBunt() *storage.DB {
|
||||
// create bunt database
|
||||
bunt := storage.NewBunt(file)
|
||||
bunt := storage.NewBunt(internal.Configuration.Database.BuntDbPath)
|
||||
// create bunt database index for ascending (searching) TipTooltips
|
||||
err := bunt.CreateIndex(MessageOrderedByReplyToFrom, TipTooltipKeyPattern, buntdb.IndexJSON(MessageOrderedByReplyToFrom))
|
||||
if err != nil {
|
||||
@@ -46,42 +38,16 @@ 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 anon_id database migrations ...")
|
||||
log.Info("Running ano_id database migrations ...")
|
||||
// run the migration on anon_id
|
||||
err = database.MigrateAnonIdInt32Hash(db)
|
||||
err = database.MigrateAnonIdHash(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
|
||||
}
|
||||
@@ -113,10 +79,6 @@ func AutoMigration() (db *gorm.DB, txLogger *gorm.DB) {
|
||||
|
||||
func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.User, error) {
|
||||
toUserDb := &lnbits.User{}
|
||||
// return error if username is too long
|
||||
if len(toUserStrWithoutAt) > 100 {
|
||||
return nil, fmt.Errorf("[GetUserByTelegramUsername] Telegram username is too long: %s..", toUserStrWithoutAt[:100])
|
||||
}
|
||||
tx := bot.Database.Where("telegram_username = ? COLLATE NOCASE", toUserStrWithoutAt).First(toUserDb)
|
||||
if tx.Error != nil || toUserDb.Wallet == nil {
|
||||
err := tx.Error
|
||||
@@ -128,7 +90,7 @@ func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.U
|
||||
return toUserDb, nil
|
||||
}
|
||||
func getCachedUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
|
||||
user := &lnbits.User{Name: strconv.Itoa(u.ID)}
|
||||
if us, err := bot.Cache.Get(user.Name); err == nil {
|
||||
return us.(*lnbits.User), nil
|
||||
}
|
||||
@@ -143,7 +105,7 @@ func getCachedUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
// &tb.User{ID: toId, Username: username}
|
||||
// without updating the user in storage.
|
||||
func GetLnbitsUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
|
||||
user := &lnbits.User{Name: strconv.Itoa(u.ID)}
|
||||
tx := bot.Database.First(user)
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[GetUser] Couldn't fetch %s from Database: %s", GetUserStr(u), tx.Error.Error())
|
||||
@@ -187,62 +149,16 @@ 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))
|
||||
log.Errorln(errmsg)
|
||||
return tx.Error
|
||||
}
|
||||
log.Tracef("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
|
||||
log.Debugf("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
|
||||
if bot.Cache.GoCacheStore != nil {
|
||||
updateCachedUser(user, bot)
|
||||
}
|
||||
|
||||
+11
-17
@@ -8,13 +8,11 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
// PLEASE DO NOT CHANGE THE CODE IN THIS FILE
|
||||
@@ -34,35 +32,35 @@ func helpDonateUsage(ctx context.Context, errormsg string) string {
|
||||
}
|
||||
}
|
||||
|
||||
func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
// 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
|
||||
_, err = bot.askForAmount(ctx, "", "CreateDonationState", 0, 0, m.Text)
|
||||
return ctx, err
|
||||
bot.askForAmount(ctx, "", "CreateDonationState", 0, 0, m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// command is valid
|
||||
msg := bot.trySendMessageEditable(m.Chat, Translate(ctx, "donationProgressMessage"))
|
||||
msg := bot.trySendMessage(user.Telegram, 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 ctx, err
|
||||
return
|
||||
}
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
// send donation invoice
|
||||
@@ -74,14 +72,10 @@ func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) (context.C
|
||||
errmsg := fmt.Sprintf("[/donate] Donation failed for user %s: %s", userStr, err)
|
||||
log.Errorln(errmsg)
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
// 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
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationSuccess"))
|
||||
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var editStack cmap.ConcurrentMap
|
||||
|
||||
type edit struct {
|
||||
to tb.Editable
|
||||
key string
|
||||
what interface{}
|
||||
options []interface{}
|
||||
lastEdit time.Time
|
||||
edited bool
|
||||
}
|
||||
|
||||
func init() {
|
||||
editStack = cmap.New()
|
||||
}
|
||||
|
||||
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.
|
||||
func (bot TipBot) startEditWorker() {
|
||||
go func() {
|
||||
for {
|
||||
for _, k := range editStack.Keys() {
|
||||
if e, ok := editStack.Get(k); ok {
|
||||
editFromStack := e.(edit)
|
||||
if !editFromStack.edited {
|
||||
_, err := bot.tryEditMessage(editFromStack.to, editFromStack.what, editFromStack.options...)
|
||||
if err != nil && 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)
|
||||
}
|
||||
} else {
|
||||
if editFromStack.lastEdit.Before(time.Now().Add(-(time.Duration(5) * time.Second))) {
|
||||
log.Tracef("[startEditWorker] removing message edit from stack %+v. len(editStack)=%d", editFromStack, len(editStack.Keys()))
|
||||
editStack.Remove(k)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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, 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("[tryEditStack] Message already in edit stack. Skipping")
|
||||
return
|
||||
}
|
||||
}
|
||||
e := edit{options: options, key: key, what: what, to: to}
|
||||
|
||||
editStack.Set(key, e)
|
||||
log.Tracef("[tryEditStack] Added message %s to edit stack. len(editStack)=%d", key, len(editStack.Keys()))
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
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) (context.Context, error) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
user := LoadUser(ctx)
|
||||
if c := stateCallbackMessage[user.StateKey]; c != nil {
|
||||
// found handler for this state
|
||||
// now looking for user state reset ticker
|
||||
ticker := runtime.GetTicker(user.ID)
|
||||
if !ticker.Started {
|
||||
ticker.Do(func() {
|
||||
ResetUserState(user, bot)
|
||||
// removing ticker asap done
|
||||
bot.shopViewDeleteAllStatusMsgs(ctx, user)
|
||||
runtime.RemoveTicker(user.ID)
|
||||
})
|
||||
} else {
|
||||
ticker.ResetChan <- struct{}{}
|
||||
}
|
||||
|
||||
return c(ctx, m)
|
||||
}
|
||||
return ctx, errors.Create(errors.NoFileFoundError)
|
||||
}
|
||||
+87
-781
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot TipBot) makeHelpMessage(ctx context.Context, m *tb.Message) string {
|
||||
@@ -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) (context.Context, error) {
|
||||
func (bot TipBot) helpHandler(ctx context.Context, m *tb.Message) {
|
||||
// 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) (context.Conte
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
bot.trySendMessage(m.Sender, bot.makeHelpMessage(ctx, m), tb.NoPreview)
|
||||
return ctx, nil
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) basicsHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
func (bot TipBot) basicsHandler(ctx context.Context, m *tb.Message) {
|
||||
// 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) (context.Con
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "basicsMessage"), tb.NoPreview)
|
||||
return ctx, nil
|
||||
return
|
||||
}
|
||||
|
||||
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) (context.Context, error) {
|
||||
func (bot TipBot) advancedHelpHandler(ctx context.Context, m *tb.Message) {
|
||||
// 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) (conte
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
bot.trySendMessage(m.Sender, bot.makeAdvancedHelpMessage(ctx, m), tb.NoPreview)
|
||||
return ctx, nil
|
||||
return
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ func GetMemoFromCommand(command string, fromWord int) string {
|
||||
return memo
|
||||
}
|
||||
|
||||
func MakeProgressbar(current int64, total int64) string {
|
||||
func MakeProgressbar(current int, total int) string {
|
||||
MAX_BARS := 16
|
||||
progress := math.Round((float64(current) / float64(total)) * float64(MAX_BARS))
|
||||
progressbar := strings.Repeat("🟩", int(progress))
|
||||
@@ -42,7 +42,7 @@ func MakeProgressbar(current int64, total int64) string {
|
||||
return progressbar
|
||||
}
|
||||
|
||||
func MakeTipjarbar(current int64, total int64) string {
|
||||
func MakeTipjarbar(current int, total int) string {
|
||||
MAX_BARS := 16
|
||||
progress := math.Round((float64(current) / float64(total)) * float64(MAX_BARS))
|
||||
progressbar := strings.Repeat("🍯", int(progress))
|
||||
|
||||
@@ -3,23 +3,17 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/once"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -29,11 +23,11 @@ var (
|
||||
)
|
||||
|
||||
type InlineFaucet struct {
|
||||
*storage.Base
|
||||
*transaction.Base
|
||||
Message string `json:"inline_faucet_message"`
|
||||
Amount int64 `json:"inline_faucet_amount"`
|
||||
RemainingAmount int64 `json:"inline_faucet_remainingamount"`
|
||||
PerUserAmount int64 `json:"inline_faucet_peruseramount"`
|
||||
Amount int `json:"inline_faucet_amount"`
|
||||
RemainingAmount int `json:"inline_faucet_remainingamount"`
|
||||
PerUserAmount int `json:"inline_faucet_peruseramount"`
|
||||
From *lnbits.User `json:"inline_faucet_from"`
|
||||
To []*lnbits.User `json:"inline_faucet_to"`
|
||||
Memo string `json:"inline_faucet_memo"`
|
||||
@@ -64,10 +58,10 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.InvalidAmountError, err)
|
||||
}
|
||||
if perUserAmount < 5 || amount%perUserAmount != 0 {
|
||||
if perUserAmount < 1 || amount%perUserAmount != 0 {
|
||||
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("invalid amount per user"))
|
||||
}
|
||||
nTotal := int(amount / perUserAmount)
|
||||
nTotal := amount / perUserAmount
|
||||
fromUser := LoadUser(ctx)
|
||||
fromUserStr := GetUserStr(sender)
|
||||
balance, err := bot.GetUserBalanceCached(fromUser)
|
||||
@@ -76,19 +70,19 @@ func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User
|
||||
}
|
||||
// check if fromUser has balance
|
||||
if balance < amount {
|
||||
return nil, errors.New(errors.BalanceToLowError, fmt.Errorf("[faucet] Balance of user %s too low", fromUserStr))
|
||||
return nil, errors.New(errors.BalanceToLowError, fmt.Errorf("[faucet] Balance of user %s too low: %v", fromUserStr, err))
|
||||
}
|
||||
// // check for memo in command
|
||||
memo := GetMemoFromCommand(text, 3)
|
||||
|
||||
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineFaucetMessage"), perUserAmount, GetUserStrMd(sender), amount, amount, 0, nTotal, MakeProgressbar(amount, amount))
|
||||
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineFaucetMessage"), perUserAmount, amount, amount, 0, nTotal, MakeProgressbar(amount, amount))
|
||||
if len(memo) > 0 {
|
||||
inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineFaucetAppendMemo"), memo)
|
||||
}
|
||||
id := fmt.Sprintf("faucet:%s:%d", RandStringRunes(10), amount)
|
||||
id := fmt.Sprintf("inl-faucet-%d-%d-%s", sender.ID, amount, RandStringRunes(5))
|
||||
|
||||
return &InlineFaucet{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
Message: inlineMessage,
|
||||
Amount: amount,
|
||||
From: fromUser,
|
||||
@@ -165,9 +159,11 @@ 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", id)
|
||||
cancelInlineFaucetButton := inlineFaucetMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_faucet_inline", id)
|
||||
// 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.Inline(
|
||||
inlineFaucetMenu.Row(
|
||||
acceptInlineFaucetButton,
|
||||
@@ -176,34 +172,35 @@ func (bot TipBot) makeFaucetKeyboard(ctx context.Context, id string) *tb.ReplyMa
|
||||
return inlineFaucetMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) faucetHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
func (bot TipBot) faucetHandler(ctx context.Context, m *tb.Message) {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if m.Private() {
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetHelpFaucetInGroup")))
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
return
|
||||
}
|
||||
ctx = bot.mapFaucetLanguage(ctx, m.Text)
|
||||
inlineFaucet, err := bot.makeFaucet(ctx, m, false)
|
||||
if err != nil {
|
||||
log.Warnf("[faucet] %s", err.Error())
|
||||
return ctx, err
|
||||
log.Errorf("[faucet] %s", err)
|
||||
return
|
||||
}
|
||||
fromUserStr := GetUserStr(m.Sender)
|
||||
mFaucet := bot.trySendMessage(m.Chat, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
|
||||
log.Infof("[faucet] %s created faucet %s: %d sat (%d per user)", fromUserStr, inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
|
||||
faucetMsg := bot.trySendMessage(m.Chat, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
|
||||
|
||||
// log faucet link if possible
|
||||
if mFaucet != nil && mFaucet.Chat != nil {
|
||||
log.Infof("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(mFaucet.Chat.ID, 10)[4:], mFaucet.ID)
|
||||
}
|
||||
return ctx, inlineFaucet.Set(inlineFaucet, bot.Bunt)
|
||||
inlineFaucet.Base.MessageID = fmt.Sprint(faucetMsg.ID)
|
||||
inlineFaucet.Base.ChatID = fmt.Sprint(-faucetMsg.Chat.ID)
|
||||
inlineFaucet.Base.MessageURL = fmt.Sprintf("https://t.me/c/%s/%s", inlineFaucet.ChatID[3:], inlineFaucet.Base.MessageID)
|
||||
|
||||
bot.trySendMessage(m.Chat, inlineFaucet.Base.MessageURL)
|
||||
log.Infof("[faucet] %s created faucet %s: %d sat (%d per user)", fromUserStr, inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
|
||||
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) (context.Context, error) {
|
||||
func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
|
||||
inlineFaucet, err := bot.makeQueryFaucet(ctx, q, false)
|
||||
if err != nil {
|
||||
log.Errorf("[handleInlineFaucetQuery] %s", err.Error())
|
||||
return ctx, err
|
||||
// log.Errorf("[faucet] %s", err)
|
||||
return
|
||||
}
|
||||
urls := []string{
|
||||
queryImage,
|
||||
@@ -223,8 +220,8 @@ func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) (con
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(inlineFaucet.ID)
|
||||
|
||||
bot.Cache.Set(inlineFaucet.ID, inlineFaucet, &store.Options{Expiration: 5 * time.Minute})
|
||||
log.Infof("[faucet] %s:%d created inline faucet %s: %d sat (%d per user)", GetUserStr(inlineFaucet.From.Telegram), inlineFaucet.From.Telegram.ID, inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
|
||||
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
|
||||
log.Infof("[faucet] %s created inline faucet %s: %d sat (%d per user)", GetUserStr(inlineFaucet.From.Telegram), inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
|
||||
}
|
||||
|
||||
err = bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
@@ -232,54 +229,45 @@ func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) (con
|
||||
CacheTime: 1,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return ctx, err
|
||||
log.Errorln(err)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
|
||||
func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
|
||||
to := LoadUser(ctx)
|
||||
tx := &InlineFaucet{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
tx := &InlineFaucet{Base: transaction.New(transaction.ID(c.Data))}
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptInlineFaucetHandler] c.Data: %s, Error: %s", c.Data, err.Error())
|
||||
return ctx, err
|
||||
log.Errorf("[faucet] %s", err)
|
||||
return
|
||||
}
|
||||
log.Tracef("[acceptInlineFaucetHandler] Callback c.Data: %s tx.ID: %s", c.Data, tx.ID)
|
||||
|
||||
inlineFaucet := fn.(*InlineFaucet)
|
||||
from := inlineFaucet.From
|
||||
// failsafe for queued users
|
||||
err = inlineFaucet.Lock(inlineFaucet, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[faucet] LockFaucet %s error: %s", inlineFaucet.ID, err)
|
||||
return
|
||||
}
|
||||
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)
|
||||
log.Errorf(fmt.Sprintf("[faucet] faucet %s inactive.", inlineFaucet.ID))
|
||||
return
|
||||
}
|
||||
// release faucet no matter what
|
||||
defer inlineFaucet.Release(inlineFaucet, bot.Bunt)
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
log.Debugf("[faucet] %s is the owner faucet %s", GetUserStr(to.Telegram), inlineFaucet.ID)
|
||||
ctx = context.WithValue(ctx, "callback_response", Translate(ctx, "sendYourselfMessage"))
|
||||
return ctx, errors.Create(errors.SelfPaymentError)
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return
|
||||
}
|
||||
// check if to user has already taken from the faucet
|
||||
for _, a := range inlineFaucet.To {
|
||||
if a.Telegram.ID == to.Telegram.ID {
|
||||
// to user is already in To slice, has taken from facuet
|
||||
log.Debugf("[faucet] %s:%d already took from faucet %s", GetUserStr(to.Telegram), to.Telegram.ID, inlineFaucet.ID)
|
||||
ctx = context.WithValue(ctx, "callback_response", Translate(ctx, "inlineFaucetAlreadyTookMessage"))
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
// log.Infof("[faucet] %s already took from faucet %s", GetUserStr(to.Telegram), inlineFaucet.ID)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
defer inlineFaucet.Set(inlineFaucet, bot.Bunt)
|
||||
|
||||
if inlineFaucet.RemainingAmount >= inlineFaucet.PerUserAmount {
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
@@ -288,11 +276,12 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
|
||||
// check if user exists and create a wallet if not
|
||||
_, exists := bot.UserExists(to.Telegram)
|
||||
if !exists {
|
||||
log.Infof("[faucet] User %s has no wallet.", toUserStr)
|
||||
to, err = bot.CreateWalletForTelegramUser(to.Telegram)
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[faucet] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,110 +296,64 @@ func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback
|
||||
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
// bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
|
||||
errMsg := fmt.Sprintf("[faucet] Transaction failed: %s", err.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
|
||||
bot.finishFaucet(ctx, c, inlineFaucet)
|
||||
return ctx, errors.New(errors.UnknownError, err)
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
|
||||
errMsg := fmt.Sprintf("[faucet] Transaction failed: %s", err)
|
||||
log.Errorln(errMsg)
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[💸 faucet] Faucet %s from %s to %s:%d (%d sat).", inlineFaucet.ID, fromUserStr, toUserStr, to.Telegram.ID, inlineFaucet.PerUserAmount)
|
||||
log.Infof("[faucet] faucet %s: %d sat from %s to %s ", inlineFaucet.ID, inlineFaucet.PerUserAmount, fromUserStr, toUserStr)
|
||||
inlineFaucet.NTaken += 1
|
||||
inlineFaucet.To = append(inlineFaucet.To, to)
|
||||
inlineFaucet.RemainingAmount = inlineFaucet.RemainingAmount - inlineFaucet.PerUserAmount
|
||||
go func() {
|
||||
to_message := fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineFaucetReceivedMessage"), fromUserStrMd, inlineFaucet.PerUserAmount)
|
||||
ctx = context.WithValue(ctx, "callback_response", to_message)
|
||||
bot.trySendMessage(to.Telegram, to_message)
|
||||
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineFaucetSentMessage"), inlineFaucet.PerUserAmount, toUserStrMd))
|
||||
}()
|
||||
|
||||
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineFaucetReceivedMessage"), fromUserStrMd, inlineFaucet.PerUserAmount))
|
||||
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineFaucetSentMessage"), inlineFaucet.PerUserAmount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[faucet] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// build faucet message
|
||||
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))
|
||||
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetMessage"), inlineFaucet.PerUserAmount, 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"), GetUserStr(bot.Telegram.Me))
|
||||
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(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 {
|
||||
bot.tryEditStack(c.Message, inlineFaucet.ID, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
|
||||
}
|
||||
|
||||
bot.tryEditMessage(c.Message, 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)
|
||||
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetEndedMessage"), inlineFaucet.Amount, inlineFaucet.NTaken)
|
||||
if inlineFaucet.UserNeedsWallet {
|
||||
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
bot.tryEditMessage(c.Message, inlineFaucet.Message)
|
||||
inlineFaucet.Active = false
|
||||
}
|
||||
return ctx, nil
|
||||
|
||||
}
|
||||
|
||||
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)
|
||||
func (bot *TipBot) cancelInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineFaucet{Base: transaction.New(transaction.ID(c.Data))}
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Debugf("[cancelInlineFaucetHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
log.Errorf("[cancelInlineSendHandler] %s", err)
|
||||
return
|
||||
}
|
||||
|
||||
inlineFaucet := fn.(*InlineFaucet)
|
||||
if ignoreID || c.Sender.ID == inlineFaucet.From.Telegram.ID {
|
||||
faucet_cancelled_message := i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage")
|
||||
bot.tryEditStack(c.Message, inlineFaucet.ID, faucet_cancelled_message, &tb.ReplyMarkup{})
|
||||
ctx = context.WithValue(ctx, "callback_response", faucet_cancelled_message)
|
||||
if c.Sender.ID == inlineFaucet.From.Telegram.ID {
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineFaucet inactive
|
||||
inlineFaucet.Active = false
|
||||
inlineFaucet.Canceled = true
|
||||
err = inlineFaucet.Set(inlineFaucet, bot.Bunt)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
log.Debugf("[faucet] Faucet %s canceled.", inlineFaucet.ID)
|
||||
once.Remove(inlineFaucet.ID)
|
||||
inlineFaucet.InTransaction = false
|
||||
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) finishFaucet(ctx context.Context, c *tb.Callback, inlineFaucet *InlineFaucet) {
|
||||
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetEndedMessage"), inlineFaucet.Amount, inlineFaucet.NTaken)
|
||||
if inlineFaucet.UserNeedsWallet {
|
||||
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
bot.tryEditStack(c.Message, inlineFaucet.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 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)
|
||||
return
|
||||
}
|
||||
@@ -3,22 +3,18 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
i18n2 "github.com/nicksnyder/go-i18n/v2/i18n"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
const queryImage = "https://avatars.githubusercontent.com/u/88730856?v=4"
|
||||
|
||||
func (bot TipBot) inlineQueryInstructions(ctx context.Context, q *tb.Query) (context.Context, error) {
|
||||
func (bot TipBot) inlineQueryInstructions(ctx context.Context, q *tb.Query) {
|
||||
instructions := []struct {
|
||||
url string
|
||||
title string
|
||||
@@ -70,7 +66,6 @@ func (bot TipBot) inlineQueryInstructions(ctx context.Context, q *tb.Query) (con
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
func (bot TipBot) inlineQueryReplyWithError(q *tb.Query, message string, help string) {
|
||||
@@ -96,23 +91,8 @@ func (bot TipBot) inlineQueryReplyWithError(q *tb.Query, message string, help st
|
||||
}
|
||||
}
|
||||
|
||||
// anyChosenInlineHandler will load any inline object from cache and store into bunt.
|
||||
// this is used to decrease bunt db write ops.
|
||||
func (bot TipBot) anyChosenInlineHandler(q *tb.ChosenInlineResult) {
|
||||
// load inline object from cache
|
||||
inlineObject, err := bot.Cache.Get(q.ResultID)
|
||||
// check error
|
||||
if err != nil {
|
||||
log.Errorf("[anyChosenInlineHandler] could not find inline object in cache. %v", err.Error())
|
||||
return
|
||||
}
|
||||
switch inlineObject.(type) {
|
||||
case storage.Storable:
|
||||
// persist inline object in bunt
|
||||
runtime.IgnoreError(bot.Bunt.Set(inlineObject.(storage.Storable)))
|
||||
default:
|
||||
log.Errorf("[anyChosenInlineHandler] invalid inline object type: %s, query: %s", reflect.TypeOf(inlineObject).String(), q.Query)
|
||||
}
|
||||
fmt.Printf(q.Query)
|
||||
}
|
||||
|
||||
func (bot TipBot) commandTranslationMap(ctx context.Context, command string) context.Context {
|
||||
@@ -134,9 +114,10 @@ func (bot TipBot) commandTranslationMap(ctx context.Context, command string) con
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (bot TipBot) anyQueryHandler(ctx context.Context, q *tb.Query) (context.Context, error) {
|
||||
func (bot TipBot) anyQueryHandler(ctx context.Context, q *tb.Query) {
|
||||
if q.Text == "" {
|
||||
return bot.inlineQueryInstructions(ctx, q)
|
||||
bot.inlineQueryInstructions(ctx, q)
|
||||
return
|
||||
}
|
||||
|
||||
// create the inline send result
|
||||
@@ -144,7 +125,7 @@ func (bot TipBot) anyQueryHandler(ctx context.Context, q *tb.Query) (context.Con
|
||||
q.Text = strings.TrimPrefix(q.Text, "/")
|
||||
}
|
||||
if strings.HasPrefix(q.Text, "send") || strings.HasPrefix(q.Text, "pay") {
|
||||
return bot.handleInlineSendQuery(ctx, q)
|
||||
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,18 +133,17 @@ func (bot TipBot) anyQueryHandler(ctx context.Context, q *tb.Query) (context.Con
|
||||
c := strings.Split(q.Text, " ")[0]
|
||||
ctx = bot.commandTranslationMap(ctx, c)
|
||||
}
|
||||
return bot.handleInlineFaucetQuery(ctx, q)
|
||||
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)
|
||||
}
|
||||
return bot.handleInlineTipjarQuery(ctx, q)
|
||||
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") {
|
||||
return bot.handleInlineReceiveQuery(ctx, q)
|
||||
bot.handleInlineReceiveQuery(ctx, q)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -1,25 +1,17 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
"github.com/skip2/go-qrcode"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -29,10 +21,9 @@ var (
|
||||
)
|
||||
|
||||
type InlineReceive struct {
|
||||
*storage.Base
|
||||
MessageText string `json:"inline_receive_messagetext"`
|
||||
Message *tb.Message `json:"inline_receive_message"`
|
||||
Amount int64 `json:"inline_receive_amount"`
|
||||
*transaction.Base
|
||||
Message string `json:"inline_receive_message"`
|
||||
Amount int `json:"inline_receive_amount"`
|
||||
From *lnbits.User `json:"inline_receive_from"`
|
||||
To *lnbits.User `json:"inline_receive_to"`
|
||||
From_SpecificUser bool `json:"from_specific_user"`
|
||||
@@ -41,30 +32,28 @@ 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
|
||||
cancelInlineReceiveButton.Data = id
|
||||
inlineReceiveMenu.Inline(
|
||||
inlineReceiveMenu.Row(
|
||||
cancelInlineReceiveButton,
|
||||
acceptInlineReceiveButton,
|
||||
),
|
||||
cancelInlineReceiveButton),
|
||||
)
|
||||
return inlineReceiveMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) (context.Context, error) {
|
||||
func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
|
||||
to := LoadUser(ctx)
|
||||
amount, err := decodeAmountFromCommand(q.Text)
|
||||
if err != nil {
|
||||
bot.inlineQueryReplyWithError(q, Translate(ctx, "inlineQueryReceiveTitle"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
if amount < 1 {
|
||||
bot.inlineQueryReplyWithError(q, Translate(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
return
|
||||
}
|
||||
toUserStr := GetUserStr(&q.From)
|
||||
|
||||
@@ -84,7 +73,7 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) (co
|
||||
fmt.Sprintf(TranslateUser(ctx, "sendUserHasNoWalletMessage"), from_username),
|
||||
fmt.Sprintf(TranslateUser(ctx, "inlineQueryReceiveDescription"),
|
||||
bot.Telegram.Me.Username))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
memo_argn = 3 // assume that memo starts after the from_username
|
||||
from_SpecificUser = true
|
||||
@@ -123,8 +112,8 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) (co
|
||||
results[i].SetResultID(id)
|
||||
// create persistend inline send struct
|
||||
inlineReceive := InlineReceive{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
MessageText: inlineMessage,
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
Message: inlineMessage,
|
||||
To: to,
|
||||
Memo: memo,
|
||||
Amount: amount,
|
||||
@@ -132,7 +121,7 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) (co
|
||||
From_SpecificUser: from_SpecificUser,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
bot.Cache.Set(inlineReceive.ID, inlineReceive, &store.Options{Expiration: 5 * time.Minute})
|
||||
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
|
||||
}
|
||||
|
||||
err = bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
@@ -142,105 +131,70 @@ func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) (co
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
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)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineReceive{Base: transaction.New(transaction.ID(c.Data))}
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
log.Errorf("[getInlineReceive] %s", err.Error())
|
||||
return ctx, err
|
||||
log.Errorf("[getInlineReceive] %s", err)
|
||||
return
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
err = inlineReceive.Lock(inlineReceive, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptInlineReceiveHandler] %s", err)
|
||||
return
|
||||
}
|
||||
|
||||
if !inlineReceive.Active {
|
||||
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
return
|
||||
}
|
||||
|
||||
defer inlineReceive.Release(inlineReceive, bot.Bunt)
|
||||
|
||||
// user `from` is the one who is SENDING
|
||||
// user `to` is the one who is RECEIVING
|
||||
from := LoadUser(ctx)
|
||||
if from.Wallet == nil {
|
||||
return
|
||||
}
|
||||
// check if this payment is requested from a specific user
|
||||
if inlineReceive.From_SpecificUser {
|
||||
if inlineReceive.From.Telegram.ID != from.Telegram.ID {
|
||||
// log.Infof("User %d is not User %d", inlineReceive.From.Telegram.ID, from.Telegram.ID)
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// otherwise, we just set it to the user who has clicked
|
||||
inlineReceive.From = from
|
||||
|
||||
}
|
||||
inlineReceive.Message = c.Message
|
||||
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
|
||||
|
||||
to := inlineReceive.To
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return ctx, errors.Create(errors.SelfPaymentError)
|
||||
}
|
||||
|
||||
balance, err := bot.GetUserBalance(from)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[inlineReceive] Error: Could not get user balance: %s", err.Error())
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
|
||||
if from.Wallet == nil || balance < inlineReceive.Amount {
|
||||
// if user has no wallet, show invoice
|
||||
bot.tryEditMessage(inlineReceive.Message, inlineReceive.MessageText, &tb.ReplyMarkup{})
|
||||
// runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
|
||||
bot.inlineReceiveInvoice(ctx, c, inlineReceive)
|
||||
return ctx, errors.Create(errors.BalanceToLowError)
|
||||
} else {
|
||||
// else, do an internal transaction
|
||||
return bot.sendInlineReceiveHandler(ctx, c)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
// log.Errorf("[getInlineReceive] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
|
||||
if !inlineReceive.Active {
|
||||
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
|
||||
// defer inlineReceive.Release(inlineReceive, bot.Bunt)
|
||||
|
||||
// from := inlineReceive.From
|
||||
from := LoadUser(ctx)
|
||||
to := inlineReceive.To
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return
|
||||
}
|
||||
// balance check of the user
|
||||
balance, err := bot.GetUserBalanceCached(from)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
// 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 ctx, errors.Create(errors.BalanceToLowError)
|
||||
return
|
||||
}
|
||||
|
||||
// set inactive to avoid double-sends
|
||||
@@ -252,115 +206,50 @@ func (bot *TipBot) sendInlineReceiveHandler(ctx context.Context, c *tb.Callback)
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
errMsg := fmt.Sprintf("[acceptInlineReceiveHandler] Transaction failed: %s", err.Error())
|
||||
errMsg := fmt.Sprintf("[acceptInlineReceiveHandler] Transaction failed: %s", err)
|
||||
log.Errorln(errMsg)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveFailedMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
|
||||
log.Infof("[💸 inlineReceive] Send from %s to %s (%d sat).", fromUserStr, toUserStr, inlineReceive.Amount)
|
||||
inlineReceive.Set(inlineReceive, bot.Bunt)
|
||||
return bot.finishInlineReceiveHandler(ctx, c)
|
||||
|
||||
}
|
||||
|
||||
func (bot *TipBot) inlineReceiveInvoice(ctx context.Context, c *tb.Callback, inlineReceive *InlineReceive) {
|
||||
if !inlineReceive.Active {
|
||||
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
|
||||
return
|
||||
}
|
||||
invoice, err := bot.createInvoiceWithEvent(ctx, inlineReceive.To, inlineReceive.Amount, fmt.Sprintf("Pay to %s", GetUserStr(inlineReceive.To.Telegram)), InvoiceCallbackInlineReceive, inlineReceive.ID)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
bot.tryEditMessage(inlineReceive.Message, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
bot.tryEditMessage(inlineReceive.Message, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
log.Infof("[acceptInlineReceiveHandler] %d sat from %s to %s", inlineReceive.Amount, fromUserStr, toUserStr)
|
||||
|
||||
// send the invoice data to user
|
||||
var msg *tb.Message
|
||||
if inlineReceive.Message.Chat != nil {
|
||||
msg = bot.trySendMessage(inlineReceive.Message.Chat, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
} else {
|
||||
msg = bot.trySendMessage(c.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
bot.tryEditMessage(inlineReceive.Message, fmt.Sprintf("%s\n\nPay this invoice:\n```%s```", inlineReceive.MessageText, invoice.PaymentRequest))
|
||||
}
|
||||
invoice.InvoiceMessage = msg
|
||||
runtime.IgnoreError(bot.Bunt.Set(invoice))
|
||||
log.Printf("[/invoice] Incvoice created. User: %s, amount: %d sat.", GetUserStr(inlineReceive.To.Telegram), inlineReceive.Amount)
|
||||
|
||||
}
|
||||
func (bot *TipBot) inlineReceiveEvent(invoiceEvent *InvoiceEvent) {
|
||||
bot.tryDeleteMessage(invoiceEvent.InvoiceMessage)
|
||||
bot.notifyInvoiceReceivedEvent(invoiceEvent)
|
||||
bot.finishInlineReceiveHandler(nil, &tb.Callback{Data: string(invoiceEvent.CallbackData)})
|
||||
}
|
||||
|
||||
func (bot *TipBot) finishInlineReceiveHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
|
||||
tx := &InlineReceive{Base: storage.New(storage.ID(c.Data))}
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[getInlineReceive] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
|
||||
from := inlineReceive.From
|
||||
to := inlineReceive.To
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
inlineReceive.MessageText = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendUpdateMessageAccept"), inlineReceive.Amount, fromUserStrMd, toUserStrMd))
|
||||
inlineReceive.Message = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendUpdateMessageAccept"), inlineReceive.Amount, fromUserStrMd, toUserStrMd))
|
||||
memo := inlineReceive.Memo
|
||||
if len(memo) > 0 {
|
||||
inlineReceive.MessageText += fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveAppendMemo"), memo)
|
||||
inlineReceive.Message = inlineReceive.Message + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveAppendMemo"), memo)
|
||||
}
|
||||
|
||||
if !to.Initialized {
|
||||
inlineReceive.MessageText += "\n\n" + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
inlineReceive.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
|
||||
bot.tryEditMessage(inlineReceive.Message, inlineReceive.MessageText, &tb.ReplyMarkup{})
|
||||
bot.tryEditMessage(c.Message, inlineReceive.Message, &tb.ReplyMarkup{})
|
||||
// notify users
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, inlineReceive.Amount))
|
||||
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), inlineReceive.Amount, toUserStrMd))
|
||||
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, inlineReceive.Amount))
|
||||
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), inlineReceive.Amount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[acceptInlineReceiveHandler] Error: Receive message to %s: %s", toUserStr, err)
|
||||
log.Warnln(errmsg)
|
||||
return ctx, err
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
return ctx, nil
|
||||
// inlineReceive.Release(inlineReceive, bot.Bunt)
|
||||
}
|
||||
|
||||
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)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
func (bot *TipBot) cancelInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineReceive{Base: transaction.New(transaction.ID(c.Data))}
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineReceiveHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
log.Errorf("[cancelInlineReceiveHandler] %s", err)
|
||||
return
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
if c.Sender.ID != inlineReceive.To.Telegram.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
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
|
||||
inlineReceive.InTransaction = false
|
||||
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
|
||||
}
|
||||
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)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -3,21 +3,16 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -27,9 +22,9 @@ var (
|
||||
)
|
||||
|
||||
type InlineSend struct {
|
||||
*storage.Base
|
||||
*transaction.Base
|
||||
Message string `json:"inline_send_message"`
|
||||
Amount int64 `json:"inline_send_amount"`
|
||||
Amount int `json:"inline_send_amount"`
|
||||
From *lnbits.User `json:"inline_send_from"`
|
||||
To *lnbits.User `json:"inline_send_to"`
|
||||
To_SpecificUser bool `json:"to_specific_user"`
|
||||
@@ -38,7 +33,6 @@ 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
|
||||
@@ -52,17 +46,17 @@ func (bot TipBot) makeSendKeyboard(ctx context.Context, id string) *tb.ReplyMark
|
||||
return inlineSendMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) (context.Context, error) {
|
||||
func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) {
|
||||
// inlineSend := NewInlineSend()
|
||||
// var err error
|
||||
amount, err := decodeAmountFromCommand(q.Text)
|
||||
if err != nil {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQuerySendTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
if amount < 1 {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
return
|
||||
}
|
||||
fromUser := LoadUser(ctx)
|
||||
fromUserStr := GetUserStr(&q.From)
|
||||
@@ -70,13 +64,13 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) (conte
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
// check if fromUser has balance
|
||||
if balance < amount {
|
||||
log.Errorf("Balance of user %s too low", fromUserStr)
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
return
|
||||
}
|
||||
|
||||
// check whether the 3rd argument is a username
|
||||
@@ -95,7 +89,7 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) (conte
|
||||
fmt.Sprintf(TranslateUser(ctx, "sendUserHasNoWalletMessage"), to_username),
|
||||
fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"),
|
||||
bot.Telegram.Me.Username))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
memo_argn = 3 // assume that memo starts after the to_username
|
||||
to_SpecificUser = true
|
||||
@@ -135,7 +129,7 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) (conte
|
||||
|
||||
// add data to persistent object
|
||||
inlineSend := InlineSend{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
Message: inlineMessage,
|
||||
From: fromUser,
|
||||
To: toUserDb,
|
||||
@@ -146,7 +140,7 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) (conte
|
||||
}
|
||||
|
||||
// add result to persistent struct
|
||||
bot.Cache.Set(inlineSend.ID, inlineSend, &store.Options{Expiration: 5 * time.Minute})
|
||||
runtime.IgnoreError(inlineSend.Set(inlineSend, bot.Bunt))
|
||||
}
|
||||
|
||||
err = bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
@@ -156,31 +150,33 @@ func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) (conte
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
|
||||
func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
to := LoadUser(ctx)
|
||||
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
tx := &InlineSend{Base: transaction.New(transaction.ID(c.Data))}
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
// log.Errorf("[acceptInlineSendHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
log.Errorf("[acceptInlineSendHandler] %s", err)
|
||||
return
|
||||
}
|
||||
inlineSend := sn.(*InlineSend)
|
||||
|
||||
fromUser := inlineSend.From
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
err = inlineSend.Lock(inlineSend, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[getInlineSend] %s", err)
|
||||
return
|
||||
}
|
||||
if !inlineSend.Active {
|
||||
log.Errorf("[acceptInlineSendHandler] inline send not active anymore")
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
return
|
||||
}
|
||||
|
||||
defer inlineSend.Set(inlineSend, bot.Bunt)
|
||||
defer inlineSend.Release(inlineSend, bot.Bunt)
|
||||
|
||||
amount := inlineSend.Amount
|
||||
|
||||
@@ -188,7 +184,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 ctx, errors.Create(errors.UnknownError)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// otherwise, we just set it to the user who has clicked
|
||||
@@ -197,7 +193,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 ctx, errors.Create(errors.UnknownError)
|
||||
return
|
||||
}
|
||||
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
@@ -213,7 +209,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 ctx, err
|
||||
return
|
||||
}
|
||||
}
|
||||
// set inactive to avoid double-sends
|
||||
@@ -225,13 +221,13 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
errMsg := fmt.Sprintf("[sendInline] Transaction failed: %s", err.Error())
|
||||
errMsg := fmt.Sprintf("[sendInline] Transaction failed: %s", err)
|
||||
log.Errorln(errMsg)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "inlineSendFailedMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[💸 sendInline] Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
log.Infof("[sendInline] %d sat from %s to %s", amount, fromUserStr, toUserStr)
|
||||
|
||||
inlineSend.Message = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineSend.LanguageCode, "inlineSendUpdateMessageAccept"), amount, fromUserStrMd, toUserStrMd))
|
||||
memo := inlineSend.Memo
|
||||
@@ -243,31 +239,30 @@ func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback)
|
||||
}
|
||||
bot.tryEditMessage(c.Message, inlineSend.Message, &tb.ReplyMarkup{})
|
||||
// notify users
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
|
||||
bot.trySendMessage(fromUser.Telegram, fmt.Sprintf(i18n.Translate(fromUser.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
|
||||
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
|
||||
_, err = bot.Telegram.Send(fromUser.Telegram, fmt.Sprintf(i18n.Translate(fromUser.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[sendInline] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Warnln(errmsg)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
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)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
func (bot *TipBot) cancelInlineSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineSend{Base: transaction.New(transaction.ID(c.Data))}
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineSendHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
log.Errorf("[cancelInlineSendHandler] %s", err)
|
||||
return
|
||||
}
|
||||
inlineSend := sn.(*InlineSend)
|
||||
if c.Sender.ID != inlineSend.From.Telegram.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
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
|
||||
inlineSend.InTransaction = false
|
||||
runtime.IgnoreError(inlineSend.Set(inlineSend, bot.Bunt))
|
||||
}
|
||||
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)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -4,19 +4,15 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -26,11 +22,11 @@ var (
|
||||
)
|
||||
|
||||
type InlineTipjar struct {
|
||||
*storage.Base
|
||||
*transaction.Base
|
||||
Message string `json:"inline_tipjar_message"`
|
||||
Amount int64 `json:"inline_tipjar_amount"`
|
||||
GivenAmount int64 `json:"inline_tipjar_givenamount"`
|
||||
PerUserAmount int64 `json:"inline_tipjar_peruseramount"`
|
||||
Amount int `json:"inline_tipjar_amount"`
|
||||
GivenAmount int `json:"inline_tipjar_givenamount"`
|
||||
PerUserAmount int `json:"inline_tipjar_peruseramount"`
|
||||
To *lnbits.User `json:"inline_tipjar_to"`
|
||||
From []*lnbits.User `json:"inline_tipjar_from"`
|
||||
Memo string `json:"inline_tipjar_memo"`
|
||||
@@ -63,7 +59,7 @@ func (bot TipBot) createTipjar(ctx context.Context, text string, sender *tb.User
|
||||
if perUserAmount < 1 || amount%perUserAmount != 0 {
|
||||
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("invalid amount per user"))
|
||||
}
|
||||
nTotal := int(amount / perUserAmount)
|
||||
nTotal := amount / perUserAmount
|
||||
toUser := LoadUser(ctx)
|
||||
// toUserStr := GetUserStr(sender)
|
||||
// // check for memo in command
|
||||
@@ -72,7 +68,7 @@ func (bot TipBot) createTipjar(ctx context.Context, text string, sender *tb.User
|
||||
inlineMessage := fmt.Sprintf(
|
||||
Translate(ctx, "inlineTipjarMessage"),
|
||||
perUserAmount,
|
||||
GetUserStrMd(toUser.Telegram),
|
||||
GetUserStr(toUser.Telegram),
|
||||
0,
|
||||
amount,
|
||||
0,
|
||||
@@ -81,10 +77,10 @@ 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("tipjar:%s:%d", RandStringRunes(10), amount)
|
||||
id := fmt.Sprintf("inl-tipjar-%d-%d-%s", sender.ID, amount, RandStringRunes(5))
|
||||
|
||||
return &InlineTipjar{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
Message: inlineMessage,
|
||||
Amount: amount,
|
||||
To: toUser,
|
||||
@@ -160,42 +156,48 @@ 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)
|
||||
buttons = append(buttons, cancelInlineTipjarButton)
|
||||
acceptInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "payReceiveButtonMessage"), "confirm_tipjar_inline", inlineTipjar.ID)
|
||||
buttons = append(buttons, acceptInlineTipjarButton)
|
||||
cancelInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_tipjar_inline", inlineTipjar.ID)
|
||||
buttons = append(buttons, cancelInlineTipjarButton)
|
||||
|
||||
inlineTipjarMenu.Inline(
|
||||
inlineTipjarMenu.Row(buttons...))
|
||||
return inlineTipjarMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) tipjarHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
func (bot TipBot) tipjarHandler(ctx context.Context, m *tb.Message) {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if m.Private() {
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineTipjarHelpText"), Translate(ctx, "inlineTipjarHelpTipjarInGroup")))
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
return
|
||||
}
|
||||
ctx = bot.mapTipjarLanguage(ctx, m.Text)
|
||||
inlineTipjar, err := bot.makeTipjar(ctx, m, false)
|
||||
if err != nil {
|
||||
log.Errorf("[tipjar] %s", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
toUserStr := GetUserStr(m.Sender)
|
||||
bot.trySendMessage(m.Chat, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
|
||||
tipjarMsg := bot.trySendMessage(m.Chat, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
|
||||
|
||||
inlineTipjar.Base.MessageID = fmt.Sprint(tipjarMsg.ID)
|
||||
inlineTipjar.Base.ChatID = fmt.Sprint(-tipjarMsg.Chat.ID)
|
||||
inlineTipjar.Base.MessageURL = fmt.Sprintf("https://t.me/c/%s/%s", inlineTipjar.ChatID[3:], inlineTipjar.Base.MessageID)
|
||||
bot.trySendMessage(m.Chat, inlineTipjar.Base.MessageURL)
|
||||
|
||||
log.Infof("[tipjar] %s created tipjar %s: %d sat (%d per user)", toUserStr, inlineTipjar.ID, inlineTipjar.Amount, inlineTipjar.PerUserAmount)
|
||||
return ctx, inlineTipjar.Set(inlineTipjar, bot.Bunt)
|
||||
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) (context.Context, error) {
|
||||
func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) {
|
||||
inlineTipjar, err := bot.makeQueryTipjar(ctx, q, false)
|
||||
if err != nil {
|
||||
// log.Errorf("[tipjar] %s", err.Error())
|
||||
return ctx, err
|
||||
// log.Errorf("[tipjar] %s", err)
|
||||
return
|
||||
}
|
||||
urls := []string{
|
||||
queryImage,
|
||||
@@ -215,7 +217,7 @@ func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) (con
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(inlineTipjar.ID)
|
||||
|
||||
bot.Cache.Set(inlineTipjar.ID, inlineTipjar, &store.Options{Expiration: 5 * time.Minute})
|
||||
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
|
||||
log.Infof("[tipjar] %s created inline tipjar %s: %d sat (%d per user)", GetUserStr(inlineTipjar.To.Telegram), inlineTipjar.ID, inlineTipjar.Amount, inlineTipjar.PerUserAmount)
|
||||
}
|
||||
|
||||
@@ -226,47 +228,46 @@ func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) (con
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
|
||||
func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback) {
|
||||
from := LoadUser(ctx)
|
||||
if from.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
tx := &InlineTipjar{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
tx := &InlineTipjar{Base: transaction.New(transaction.ID(c.Data))}
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
// log.Errorf("[tipjar] %s", err.Error())
|
||||
return ctx, err
|
||||
log.Errorf("[tipjar] %s", err)
|
||||
return
|
||||
}
|
||||
inlineTipjar := fn.(*InlineTipjar)
|
||||
to := inlineTipjar.To
|
||||
err = inlineTipjar.Lock(inlineTipjar, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[tipjar] LockTipjar %s error: %s", inlineTipjar.ID, err)
|
||||
return
|
||||
}
|
||||
if !inlineTipjar.Active {
|
||||
log.Errorf(fmt.Sprintf("[tipjar] tipjar %s inactive.", inlineTipjar.ID))
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
return
|
||||
}
|
||||
// release tipjar no matter what
|
||||
defer inlineTipjar.Release(inlineTipjar, bot.Bunt)
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return ctx, errors.Create(errors.SelfPaymentError)
|
||||
return
|
||||
}
|
||||
// // check if to user has already given to the tipjar
|
||||
for _, a := range inlineTipjar.From {
|
||||
if a.Telegram.ID == from.Telegram.ID {
|
||||
if a.Telegram.ID == to.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 ctx, errors.Create(errors.UnknownError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
defer inlineTipjar.Set(inlineTipjar, bot.Bunt)
|
||||
|
||||
if inlineTipjar.GivenAmount < inlineTipjar.Amount {
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
@@ -281,28 +282,29 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
|
||||
errMsg := fmt.Sprintf("[tipjar] Transaction failed: %s", err.Error())
|
||||
errMsg := fmt.Sprintf("[tipjar] Transaction failed: %s", err)
|
||||
log.Errorln(errMsg)
|
||||
return ctx, errors.New(errors.UnknownError, err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[💸 tipjar] Tipjar %s from %s to %s (%d sat).", inlineTipjar.ID, fromUserStr, toUserStr, inlineTipjar.PerUserAmount)
|
||||
log.Infof("[tipjar] tipjar %s: %d sat from %s to %s ", inlineTipjar.ID, inlineTipjar.PerUserAmount, fromUserStr, toUserStr)
|
||||
inlineTipjar.NGiven += 1
|
||||
inlineTipjar.From = append(inlineTipjar.From, from)
|
||||
inlineTipjar.GivenAmount = inlineTipjar.GivenAmount + inlineTipjar.PerUserAmount
|
||||
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineTipjarReceivedMessage"), fromUserStrMd, inlineTipjar.PerUserAmount))
|
||||
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineTipjarSentMessage"), inlineTipjar.PerUserAmount, toUserStrMd))
|
||||
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineTipjarReceivedMessage"), fromUserStrMd, inlineTipjar.PerUserAmount))
|
||||
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineTipjarSentMessage"), inlineTipjar.PerUserAmount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[tipjar] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Warnln(errmsg)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// build tipjar message
|
||||
inlineTipjar.Message = fmt.Sprintf(
|
||||
i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarMessage"),
|
||||
inlineTipjar.PerUserAmount,
|
||||
GetUserStrMd(inlineTipjar.To.Telegram),
|
||||
GetUserStr(inlineTipjar.To.Telegram),
|
||||
inlineTipjar.GivenAmount,
|
||||
inlineTipjar.Amount,
|
||||
inlineTipjar.NGiven,
|
||||
@@ -312,6 +314,9 @@ 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))
|
||||
@@ -320,53 +325,33 @@ func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback
|
||||
// tipjar is full
|
||||
inlineTipjar.Message = fmt.Sprintf(
|
||||
i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarEndedMessage"),
|
||||
GetUserStrMd(inlineTipjar.To.Telegram),
|
||||
GetUserStr(inlineTipjar.To.Telegram),
|
||||
inlineTipjar.Amount,
|
||||
inlineTipjar.NGiven,
|
||||
)
|
||||
// if inlineTipjar.UserNeedsWallet {
|
||||
// inlineTipjar.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
// }
|
||||
bot.tryEditMessage(c.Message, inlineTipjar.Message)
|
||||
// send update to tipjar creator
|
||||
if inlineTipjar.Active && inlineTipjar.To.Telegram.ID != 0 {
|
||||
bot.trySendMessage(inlineTipjar.To.Telegram, listTipjarGivers(inlineTipjar))
|
||||
}
|
||||
inlineTipjar.Active = false
|
||||
}
|
||||
return ctx, nil
|
||||
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineTipjarHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
|
||||
tx := &InlineTipjar{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
func (bot *TipBot) cancelInlineTipjarHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineTipjar{Base: transaction.New(transaction.ID(c.Data))}
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineTipjarHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
log.Errorf("[cancelInlineSendHandler] %s", err)
|
||||
return
|
||||
}
|
||||
inlineTipjar := fn.(*InlineTipjar)
|
||||
if c.Sender.ID != inlineTipjar.To.Telegram.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
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
|
||||
inlineTipjar.InTransaction = false
|
||||
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
|
||||
}
|
||||
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
|
||||
return
|
||||
}
|
||||
@@ -2,19 +2,17 @@ package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type CallbackFuncHandler func(ctx context.Context, message *tb.Callback) (context.Context, error)
|
||||
type CallbackFuncHandler func(ctx context.Context, message *tb.Callback)
|
||||
type Func func(ctx context.Context, message interface{}) (context.Context, error)
|
||||
|
||||
type handlerCallbackInterceptor struct {
|
||||
handler CallbackFuncHandler
|
||||
before CallbackChain
|
||||
after CallbackChain
|
||||
onDefer CallbackChain
|
||||
}
|
||||
type CallbackChain []Func
|
||||
type CallbackInterceptOption func(*handlerCallbackInterceptor)
|
||||
@@ -29,11 +27,6 @@ func WithAfterCallback(chain ...Func) CallbackInterceptOption {
|
||||
a.after = chain
|
||||
}
|
||||
}
|
||||
func WithDeferCallback(chain ...Func) CallbackInterceptOption {
|
||||
return func(a *handlerCallbackInterceptor) {
|
||||
a.onDefer = chain
|
||||
}
|
||||
}
|
||||
|
||||
func interceptCallback(ctx context.Context, message *tb.Callback, hm CallbackChain) (context.Context, error) {
|
||||
if ctx == nil {
|
||||
@@ -57,18 +50,12 @@ func HandlerWithCallback(handler CallbackFuncHandler, option ...CallbackIntercep
|
||||
opt(hm)
|
||||
}
|
||||
return func(c *tb.Callback) {
|
||||
ctx := context.Background()
|
||||
ctx, err := interceptCallback(ctx, c, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
defer interceptCallback(ctx, c, hm.onDefer)
|
||||
ctx, err = hm.handler(ctx, c)
|
||||
ctx, err := interceptCallback(context.Background(), c, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
hm.handler(ctx, c)
|
||||
_, err = interceptCallback(ctx, c, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
|
||||
@@ -2,18 +2,19 @@ package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type MessageFuncHandler func(ctx context.Context, message *tb.Message) (context.Context, error)
|
||||
type MessageInterface interface {
|
||||
a() func(ctx context.Context, message *tb.Message)
|
||||
}
|
||||
type MessageFuncHandler func(ctx context.Context, message *tb.Message)
|
||||
|
||||
type handlerMessageInterceptor struct {
|
||||
handler MessageFuncHandler
|
||||
before MessageChain
|
||||
after MessageChain
|
||||
onDefer MessageChain
|
||||
}
|
||||
type MessageChain []Func
|
||||
type MessageInterceptOption func(*handlerMessageInterceptor)
|
||||
@@ -28,11 +29,6 @@ func WithAfterMessage(chain ...Func) MessageInterceptOption {
|
||||
a.after = chain
|
||||
}
|
||||
}
|
||||
func WithDeferMessage(chain ...Func) MessageInterceptOption {
|
||||
return func(a *handlerMessageInterceptor) {
|
||||
a.onDefer = chain
|
||||
}
|
||||
}
|
||||
|
||||
func interceptMessage(ctx context.Context, message *tb.Message, hm MessageChain) (context.Context, error) {
|
||||
if ctx == nil {
|
||||
@@ -51,23 +47,18 @@ func interceptMessage(ctx context.Context, message *tb.Message, hm MessageChain)
|
||||
}
|
||||
|
||||
func HandlerWithMessage(handler MessageFuncHandler, option ...MessageInterceptOption) func(message *tb.Message) {
|
||||
|
||||
hm := &handlerMessageInterceptor{handler: handler}
|
||||
for _, opt := range option {
|
||||
opt(hm)
|
||||
}
|
||||
return func(message *tb.Message) {
|
||||
ctx := context.Background()
|
||||
ctx, err := interceptMessage(ctx, message, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
defer interceptMessage(ctx, message, hm.onDefer)
|
||||
ctx, err = hm.handler(ctx, message)
|
||||
ctx, err := interceptMessage(context.Background(), message, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
hm.handler(ctx, message)
|
||||
_, err = interceptMessage(ctx, message, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
|
||||
@@ -2,18 +2,16 @@ package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type QueryFuncHandler func(ctx context.Context, message *tb.Query) (context.Context, error)
|
||||
type QueryFuncHandler func(ctx context.Context, message *tb.Query)
|
||||
|
||||
type handlerQueryInterceptor struct {
|
||||
handler QueryFuncHandler
|
||||
before QueryChain
|
||||
after QueryChain
|
||||
onDefer QueryChain
|
||||
}
|
||||
type QueryChain []Func
|
||||
type QueryInterceptOption func(*handlerQueryInterceptor)
|
||||
@@ -28,11 +26,6 @@ func WithAfterQuery(chain ...Func) QueryInterceptOption {
|
||||
a.after = chain
|
||||
}
|
||||
}
|
||||
func WithDeferQuery(chain ...Func) QueryInterceptOption {
|
||||
return func(a *handlerQueryInterceptor) {
|
||||
a.onDefer = chain
|
||||
}
|
||||
}
|
||||
|
||||
func interceptQuery(ctx context.Context, message *tb.Query, hm QueryChain) (context.Context, error) {
|
||||
if ctx == nil {
|
||||
@@ -55,20 +48,14 @@ func HandlerWithQuery(handler QueryFuncHandler, option ...QueryInterceptOption)
|
||||
for _, opt := range option {
|
||||
opt(hm)
|
||||
}
|
||||
return func(query *tb.Query) {
|
||||
ctx := context.Background()
|
||||
ctx, err := interceptQuery(context.Background(), query, hm.before)
|
||||
return func(message *tb.Query) {
|
||||
ctx, err := interceptQuery(context.Background(), message, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
defer interceptQuery(ctx, query, hm.onDefer)
|
||||
ctx, err = hm.handler(ctx, query)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
_, err = interceptQuery(ctx, query, hm.after)
|
||||
hm.handler(ctx, message)
|
||||
_, err = interceptQuery(ctx, message, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
|
||||
@@ -3,13 +3,6 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/once"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
i18n2 "github.com/nicksnyder/go-i18n/v2/i18n"
|
||||
@@ -17,7 +10,7 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type InterceptorType int
|
||||
@@ -28,110 +21,34 @@ const (
|
||||
QueryInterceptor
|
||||
)
|
||||
|
||||
var invalidTypeError = fmt.Errorf("invalid type")
|
||||
|
||||
type Interceptor struct {
|
||||
Type InterceptorType
|
||||
Before []intercept.Func
|
||||
After []intercept.Func
|
||||
OnDefer []intercept.Func
|
||||
Type InterceptorType
|
||||
Before []intercept.Func
|
||||
After []intercept.Func
|
||||
}
|
||||
|
||||
// singletonClickInterceptor uses the onceMap to determine whether the object k1 already interacted
|
||||
// with the user k2. If so, it will return an error.
|
||||
func (bot TipBot) singletonCallbackInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
switch i.(type) {
|
||||
case *tb.Callback:
|
||||
c := i.(*tb.Callback)
|
||||
return ctx, once.Once(c.Data, strconv.FormatInt(c.Sender.ID, 10))
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
|
||||
// lockInterceptor invoked as first before interceptor
|
||||
func (bot TipBot) lockInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
user := getTelegramUserFromInterface(i)
|
||||
if user != nil {
|
||||
mutex.Lock(strconv.FormatInt(user.ID, 10))
|
||||
return ctx, nil
|
||||
}
|
||||
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
|
||||
// user is here an lnbits.User
|
||||
func (bot TipBot) requireUserInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
var user *lnbits.User
|
||||
var err error
|
||||
u := getTelegramUserFromInterface(i)
|
||||
if u != nil {
|
||||
user, err = GetUser(u, bot)
|
||||
// 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, 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
|
||||
}
|
||||
|
||||
// getTelegramUserFromInterface returns the tb user based in interface type
|
||||
func getTelegramUserFromInterface(i interface{}) (user *tb.User) {
|
||||
switch i.(type) {
|
||||
case *tb.Query:
|
||||
user = &i.(*tb.Query).From
|
||||
user, err := GetUser(&i.(*tb.Query).From, bot)
|
||||
return context.WithValue(ctx, "user", user), err
|
||||
case *tb.Callback:
|
||||
user = i.(*tb.Callback).Sender
|
||||
c := i.(*tb.Callback)
|
||||
m := *c.Message
|
||||
m.Sender = c.Sender
|
||||
user, err := GetUser(i.(*tb.Callback).Sender, bot)
|
||||
return context.WithValue(ctx, "user", user), err
|
||||
case *tb.Message:
|
||||
user = i.(*tb.Message).Sender
|
||||
default:
|
||||
log.Tracef("[getTelegramUserFromInterface] invalid type %s", reflect.TypeOf(i).String())
|
||||
user, err := GetUser(i.(*tb.Message).Sender, bot)
|
||||
return context.WithValue(ctx, "user", user), err
|
||||
}
|
||||
return
|
||||
return nil, invalidTypeError
|
||||
}
|
||||
func (bot TipBot) loadUserInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
ctx, _ = bot.requireUserInterceptor(ctx, i)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// loadReplyToInterceptor Loading the Telegram user with message intercept
|
||||
@@ -148,7 +65,7 @@ func (bot TipBot) loadReplyToInterceptor(ctx context.Context, i interface{}) (co
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
return ctx, invalidTypeError
|
||||
}
|
||||
|
||||
func (bot TipBot) localizerInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
@@ -191,11 +108,11 @@ func (bot TipBot) requirePrivateChatInterceptor(ctx context.Context, i interface
|
||||
case *tb.Message:
|
||||
m := i.(*tb.Message)
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return nil, fmt.Errorf("[requirePrivateChatInterceptor] no private chat")
|
||||
return nil, fmt.Errorf("no private chat")
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
return nil, errors.Create(errors.InvalidTypeError)
|
||||
return nil, invalidTypeError
|
||||
}
|
||||
|
||||
const photoTag = "<Photo>"
|
||||
@@ -219,7 +136,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, errors.Create(errors.InvalidTypeError)
|
||||
return nil, invalidTypeError
|
||||
}
|
||||
|
||||
// LoadUser from context
|
||||
|
||||
+22
-134
@@ -5,62 +5,16 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type InvoiceEventCallback map[int]func(*InvoiceEvent)
|
||||
|
||||
var InvoiceCallback InvoiceEventCallback
|
||||
|
||||
func initInvoiceEventCallbacks(bot *TipBot) {
|
||||
InvoiceCallback = InvoiceEventCallback{
|
||||
InvoiceCallbackGeneric: bot.notifyInvoiceReceivedEvent,
|
||||
InvoiceCallbackInlineReceive: bot.inlineReceiveEvent,
|
||||
InvoiceCallbackLNURLPayReceive: bot.lnurlReceiveEvent,
|
||||
}
|
||||
}
|
||||
|
||||
type InvoiceEventKey int
|
||||
|
||||
const (
|
||||
InvoiceCallbackGeneric = iota + 1
|
||||
InvoiceCallbackInlineReceive
|
||||
InvoiceCallbackLNURLPayReceive
|
||||
)
|
||||
|
||||
type Invoice struct {
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
PaymentRequest string `json:"payment_request"`
|
||||
Amount int64 `json:"amount"`
|
||||
Memo string `json:"memo"`
|
||||
}
|
||||
type InvoiceEvent struct {
|
||||
*Invoice
|
||||
User *lnbits.User `json:"user"`
|
||||
Message *tb.Message `json:"message"`
|
||||
InvoiceMessage *tb.Message `json:"invoice_message"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
Callback int `json:"func"`
|
||||
CallbackData string `json:"callbackdata"`
|
||||
}
|
||||
|
||||
func (invoiceEvent InvoiceEvent) Key() string {
|
||||
return fmt.Sprintf("invoice:%s", invoiceEvent.PaymentHash)
|
||||
}
|
||||
|
||||
func helpInvoiceUsage(ctx context.Context, errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(Translate(ctx, "invoiceHelpText"), fmt.Sprintf("%s", errormsg))
|
||||
@@ -69,25 +23,25 @@ func helpInvoiceUsage(ctx context.Context, errormsg string) string {
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) invoiceHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
func (bot TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
userStr := GetUserStr(user.Telegram)
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(m)
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
return
|
||||
}
|
||||
// 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
|
||||
_, err = bot.askForAmount(ctx, "", "CreateInvoiceState", 0, 0, m.Text)
|
||||
return ctx, err
|
||||
bot.askForAmount(ctx, "", "CreateInvoiceState", 0, 0, m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// check for memo in command
|
||||
@@ -102,35 +56,9 @@ func (bot *TipBot) invoiceHandler(ctx context.Context, m *tb.Message) (context.C
|
||||
memo = memo + tag
|
||||
}
|
||||
|
||||
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 ctx, err
|
||||
}
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// deleting messages will delete the main menu.
|
||||
//bot.tryDeleteMessage(creatingMsg)
|
||||
|
||||
// send the invoice data to user
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
log.Printf("[/invoice] Incvoice created. User: %s, amount: %d sat.", userStr, amount)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User, amount int64, memo string, callback int, callbackData string) (InvoiceEvent, error) {
|
||||
creatingMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
log.Infof("[/invoice] Creating invoice for %s of %d sat.", userStr, amount)
|
||||
// generate invoice
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
@@ -139,64 +67,24 @@ func (bot *TipBot) createInvoiceWithEvent(ctx context.Context, user *lnbits.User
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err)
|
||||
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return InvoiceEvent{}, err
|
||||
return
|
||||
}
|
||||
invoiceEvent := InvoiceEvent{
|
||||
Invoice: &Invoice{PaymentHash: invoice.PaymentHash,
|
||||
PaymentRequest: invoice.PaymentRequest,
|
||||
Amount: amount,
|
||||
Memo: memo},
|
||||
User: user,
|
||||
Callback: callback,
|
||||
CallbackData: callbackData,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
// save invoice struct for later use
|
||||
runtime.IgnoreError(bot.Bunt.Set(invoiceEvent))
|
||||
return invoiceEvent, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) notifyInvoiceReceivedEvent(invoiceEvent *InvoiceEvent) {
|
||||
// do balance check for keyboard update
|
||||
_, err := bot.GetUserBalance(invoiceEvent.User)
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", GetUserStr(invoiceEvent.User.Telegram))
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err)
|
||||
bot.tryEditMessage(creatingMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
bot.trySendMessage(invoiceEvent.User.Telegram, fmt.Sprintf(i18n.Translate(invoiceEvent.User.Telegram.LanguageCode, "invoiceReceivedMessage"), invoiceEvent.Amount))
|
||||
}
|
||||
|
||||
type LNURLInvoice struct {
|
||||
*Invoice
|
||||
Comment string `json:"comment"`
|
||||
User *lnbits.User `json:"user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Paid bool `json:"paid"`
|
||||
PaidAt time.Time `json:"paid_at"`
|
||||
From string `json:"from"`
|
||||
}
|
||||
|
||||
func (lnurlInvoice LNURLInvoice) Key() string {
|
||||
return fmt.Sprintf("lnurl-p:%s", lnurlInvoice.PaymentHash)
|
||||
}
|
||||
|
||||
func (bot *TipBot) lnurlReceiveEvent(invoiceEvent *InvoiceEvent) {
|
||||
bot.notifyInvoiceReceivedEvent(invoiceEvent)
|
||||
tx := &LNURLInvoice{Invoice: &Invoice{PaymentHash: invoiceEvent.PaymentHash}}
|
||||
err := bot.Bunt.Get(tx)
|
||||
log.Debugf("[lnurl-p] Received invoice for %s of %d sat.", GetUserStr(invoiceEvent.User.Telegram), tx.Amount)
|
||||
if err == nil {
|
||||
if len(tx.Comment) > 0 {
|
||||
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)))
|
||||
}
|
||||
}
|
||||
bot.tryDeleteMessage(creatingMsg)
|
||||
// send the invoice data to user
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", invoice.PaymentRequest)})
|
||||
log.Printf("[/invoice] Incvoice created. User: %s, amount: %d sat.", userStr, amount)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -4,19 +4,18 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
func (bot TipBot) lndhubHandler(ctx context.Context, m *tb.Message) {
|
||||
if internal.Configuration.Lnbits.LnbitsPublicUrl == "" {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "couldNotLinkMessage"))
|
||||
return ctx, fmt.Errorf("invalid configuration")
|
||||
return
|
||||
}
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
@@ -29,31 +28,16 @@ func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) (context.Co
|
||||
fromUser := LoadUser(ctx)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "walletConnectMessage"))
|
||||
|
||||
// do not respond to banned users
|
||||
if bot.UserIsBanned(fromUser) {
|
||||
log.Warnln("[lndhubHandler] user is banned. not responding.")
|
||||
return ctx, fmt.Errorf("user is banned")
|
||||
}
|
||||
|
||||
lndhubUrl := fmt.Sprintf("lndhub://admin:%s@%slndhub/ext/", fromUser.Wallet.Adminkey, internal.Configuration.Lnbits.LnbitsPublicUrl)
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(lndhubUrl, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err.Error())
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
// send the link to the user
|
||||
linkmsg := bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
|
||||
|
||||
go func() {
|
||||
time.Sleep(time.Second * 60)
|
||||
bot.tryDeleteMessage(linkmsg)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "linkHiddenMessage"))
|
||||
}()
|
||||
// auto delete the message
|
||||
// NewMessage(linkmsg, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
|
||||
return ctx, nil
|
||||
// send the invoice data to user
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
|
||||
}
|
||||
|
||||
@@ -1,151 +0,0 @@
|
||||
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))
|
||||
lnurlAuthState := &LnurlAuthState{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
From: user,
|
||||
LNURLAuthParams: authParams.LNURLAuthParams,
|
||||
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),
|
||||
)
|
||||
lnurlAuthState.Message = bot.trySendMessageEditable(m.Chat,
|
||||
fmt.Sprintf(Translate(ctx, "confirmLnurlAuthMessager"),
|
||||
lnurlAuthState.LNURLAuthParams.CallbackURL.Host,
|
||||
),
|
||||
paymentConfirmationMenu,
|
||||
)
|
||||
|
||||
// save to bunt
|
||||
runtime.IgnoreError(lnurlAuthState.Set(lnurlAuthState, 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)
|
||||
}
|
||||
@@ -9,135 +9,119 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
lnurl "github.com/fiatjaf/go-lnurl"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
// LnurlPayState saves the state of the user for an LNURL payment
|
||||
type LnurlPayState struct {
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLPayParams lnurl.LNURLPayParams `json:"LNURLPayParams"`
|
||||
LNURLPayValues lnurl.LNURLPayValues `json:"LNURLPayValues"`
|
||||
Amount int64 `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
*transaction.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLPayResponse1 lnurl.LNURLPayResponse1 `json:"LNURLPayResponse1"`
|
||||
LNURLPayResponse2 lnurl.LNURLPayResponse2 `json:"LNURLPayResponse2"`
|
||||
Amount int `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
}
|
||||
|
||||
// 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) (context.Context, error) {
|
||||
func (bot *TipBot) lnurlPayHandler(ctx context.Context, m *tb.Message, payParams LnurlPayState) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
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),
|
||||
id := fmt.Sprintf("lnurlp-%d-%s", m.Sender.ID, RandStringRunes(5))
|
||||
lnurlPayState := LnurlPayState{
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
LNURLPayResponse1: payParams.LNURLPayResponse1,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
|
||||
|
||||
// if no amount is in the command, ask for it
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if err != nil || amount < 1 {
|
||||
// // no amount was entered, set user state and ask for amount
|
||||
bot.askForAmount(ctx, id, "LnurlPayState", lnurlPayState.LNURLPayResponse1.MinSendable, lnurlPayState.LNURLPayResponse1.MaxSendable, m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// first we check whether an amount is present in the command
|
||||
amount, amount_err := decodeAmountFromCommand(m.Text)
|
||||
|
||||
// we need to figure out whether the memo starts at position 2 or 3
|
||||
// so either /lnurl <amount> <lnurl> [memo] or /lnurl <lnurl> [memo]
|
||||
memoStartsAt := 2
|
||||
if amount_err == nil {
|
||||
// amount was present
|
||||
memoStartsAt = 3
|
||||
// amount is already present in the command, i.e., /lnurl <amount> <LNURL>
|
||||
// amount not in allowed range from LNURL
|
||||
if int64(amount) > (lnurlPayState.LNURLPayResponse1.MaxSendable/1000) || int64(amount) < (lnurlPayState.LNURLPayResponse1.MinSendable/1000) {
|
||||
err = fmt.Errorf("amount not in range")
|
||||
log.Warnf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), lnurlPayState.LNURLPayResponse1.MinSendable/1000, lnurlPayState.LNURLPayResponse1.MaxSendable/1000))
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
}
|
||||
// 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]
|
||||
// set also amount in the state of the user
|
||||
lnurlPayState.Amount = amount * 1000 // save as mSat
|
||||
|
||||
// check if comment is presentin lnrul-p
|
||||
memo := GetMemoFromCommand(m.Text, 3)
|
||||
// shorten comment to allowed length
|
||||
if len(memo) > int(lnurlPayState.LNURLPayResponse1.CommentAllowed) {
|
||||
memo = memo[:lnurlPayState.LNURLPayResponse1.CommentAllowed]
|
||||
}
|
||||
if len(memo) > 0 {
|
||||
lnurlPayState.Comment = memo
|
||||
}
|
||||
|
||||
// amount is already present in the command, i.e., /lnurl <amount> <LNURL>
|
||||
// amount not in allowed range from LNURL
|
||||
if amount_err == nil &&
|
||||
(int64(amount) > (lnurlPayState.LNURLPayParams.MaxSendable/1000) || int64(amount) < (lnurlPayState.LNURLPayParams.MinSendable/1000)) &&
|
||||
(lnurlPayState.LNURLPayParams.MaxSendable != 0 && lnurlPayState.LNURLPayParams.MinSendable != 0) { // only if max and min are set
|
||||
err := fmt.Errorf("amount not in range")
|
||||
log.Warnf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), lnurlPayState.LNURLPayParams.MinSendable/1000, lnurlPayState.LNURLPayParams.MaxSendable/1000))
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
}
|
||||
// set also amount in the state of the user
|
||||
lnurlPayState.Amount = amount * 1000 // save as mSat
|
||||
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
|
||||
|
||||
// now we actualy check whether the amount was in the command and if not, ask for it
|
||||
if lnurlPayState.LNURLPayParams.MinSendable == lnurlPayState.LNURLPayParams.MaxSendable {
|
||||
lnurlPayState.Amount = lnurlPayState.LNURLPayParams.MaxSendable // save as mSat
|
||||
} else if amount_err != nil || amount < 1 {
|
||||
// // no amount was entered, set user state and ask for amount
|
||||
bot.askForAmount(ctx, id, "LnurlPayState", lnurlPayState.LNURLPayParams.MinSendable, lnurlPayState.LNURLPayParams.MaxSendable, m.Text)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// We need to save the pay state in the user state so we can load the payment in the next handler
|
||||
// not necessary to save this in the state data, but till doing it
|
||||
paramsJson, err := json.Marshal(lnurlPayState)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
|
||||
// directly go to confirm
|
||||
return bot.lnurlPayHandlerSend(ctx, m)
|
||||
bot.lnurlPayHandlerSend(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
// lnurlPayHandlerSend is invoked when the user has delivered an amount and is ready to pay
|
||||
func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
// lnurlPayHandler is invoked when the user has delivered an amount and is ready to pay
|
||||
func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
|
||||
// assert that user has entered an amount
|
||||
if user.StateKey != lnbits.UserHasEnteredAmount {
|
||||
log.Errorln("[lnurlPayHandlerSend] state keys don't match")
|
||||
log.Errorln("[lnurlPayHandler] state keys don't match")
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, fmt.Errorf("wrong state key")
|
||||
return
|
||||
}
|
||||
|
||||
// read the enter amount state from user.StateData
|
||||
var enterAmountData EnterAmountStateData
|
||||
err := json.Unmarshal([]byte(user.StateData), &enterAmountData)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
// use the enter amount state of the user to load the LNURL payment state
|
||||
tx := &LnurlPayState{Base: storage.New(storage.ID(enterAmountData.ID))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
tx := &LnurlPayState{Base: transaction.New(transaction.ID(enterAmountData.ID))}
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
lnurlPayState := fn.(*LnurlPayState)
|
||||
|
||||
@@ -145,19 +129,21 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) (cont
|
||||
|
||||
client, err := bot.GetHttpClient()
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
|
||||
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayResponse1.Callback)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
qs := callbackUrl.Query()
|
||||
// add amount to query string
|
||||
qs.Set("amount", strconv.FormatInt(lnurlPayState.Amount, 10)) // msat
|
||||
qs.Set("amount", strconv.Itoa(lnurlPayState.Amount)) // msat
|
||||
// add comment to query string
|
||||
if len(lnurlPayState.Comment) > 0 {
|
||||
qs.Set("comment", lnurlPayState.Comment)
|
||||
@@ -168,40 +154,42 @@ func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) (cont
|
||||
res, err := client.Get(callbackUrl.String())
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
body, err := ioutil.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
var response2 lnurl.LNURLPayValues
|
||||
var response2 lnurl.LNURLPayResponse2
|
||||
json.Unmarshal(body, &response2)
|
||||
if response2.Status == "ERROR" || len(response2.PR) < 1 {
|
||||
error_reason := "Could not receive invoice."
|
||||
if len(response2.Reason) > 0 {
|
||||
error_reason = response2.Reason
|
||||
}
|
||||
log.Errorf("[lnurlPayHandler] Error in LNURLPayValues: %s", error_reason)
|
||||
log.Errorf("[lnurlPayHandler] Error in LNURLPayResponse2: %s", error_reason)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
|
||||
return ctx, fmt.Errorf("Error in LNURLPayValues: %s", error_reason)
|
||||
return
|
||||
}
|
||||
|
||||
lnurlPayState.LNURLPayValues = response2
|
||||
lnurlPayState.LNURLPayResponse2 = response2
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
|
||||
bot.Telegram.Delete(statusMsg)
|
||||
m.Text = fmt.Sprintf("/pay %s", response2.PR)
|
||||
return bot.payHandler(ctx, m)
|
||||
bot.payHandler(ctx, m)
|
||||
}
|
||||
|
||||
func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, address string, amount int64) (context.Context, error) {
|
||||
func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, address string, amount int) error {
|
||||
split := strings.Split(address, "@")
|
||||
if len(split) != 2 {
|
||||
return ctx, fmt.Errorf("lightning address format wrong")
|
||||
return fmt.Errorf("lightning address format wrong")
|
||||
}
|
||||
host := strings.ToLower(split[1])
|
||||
name := strings.ToLower(split[0])
|
||||
@@ -213,7 +201,7 @@ func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, ad
|
||||
|
||||
lnurl, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
return err
|
||||
}
|
||||
|
||||
if amount > 0 {
|
||||
@@ -234,5 +222,5 @@ func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, ad
|
||||
m.Text = fmt.Sprintf("/lnurl %s", lnurl)
|
||||
}
|
||||
bot.lnurlHandler(ctx, m)
|
||||
return ctx, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,332 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
lnurl "github.com/fiatjaf/go-lnurl"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
withdrawConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelWithdraw = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_withdraw")
|
||||
btnWithdraw = paymentConfirmationMenu.Data("✅ Withdraw", "confirm_withdraw")
|
||||
)
|
||||
|
||||
// LnurlWithdrawState saves the state of the user for an LNURL payment
|
||||
type LnurlWithdrawState struct {
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLWithdrawResponse lnurl.LNURLWithdrawResponse `json:"LNURLWithdrawResponse"`
|
||||
LNURResponse lnurl.LNURLResponse `json:"LNURLResponse"`
|
||||
Amount int64 `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
Success bool `json:"success"`
|
||||
Invoice lnbits.BitInvoice `json:"invoice"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// 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,
|
||||
message,
|
||||
&tb.ReplyMarkup{
|
||||
InlineKeyboard: [][]tb.InlineButton{
|
||||
{tb.InlineButton{Text: button}},
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// lnurlWithdrawHandler is invoked when the first lnurl response was a lnurl-withdraw response
|
||||
// at this point, the user hans't necessarily entered an amount yet
|
||||
func (bot *TipBot) lnurlWithdrawHandler(ctx context.Context, m *tb.Message, withdrawParams LnurlWithdrawState) (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("lnurlw:%d:%s", m.Sender.ID, RandStringRunes(5))
|
||||
LnurlWithdrawState := LnurlWithdrawState{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
From: user,
|
||||
LNURLWithdrawResponse: withdrawParams.LNURLWithdrawResponse,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
|
||||
// first we check whether an amount is present in the command
|
||||
amount, amount_err := decodeAmountFromCommand(m.Text)
|
||||
|
||||
// amount is already present in the command, i.e., /lnurl <amount> <LNURL>
|
||||
// amount not in allowed range from LNURL
|
||||
if amount_err == nil &&
|
||||
(int64(amount) > (LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable/1000) || int64(amount) < (LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable/1000)) &&
|
||||
(LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable != 0 && LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable != 0) { // only if max and min are set
|
||||
err := fmt.Errorf("amount not in range")
|
||||
log.Warnf("[lnurlWithdrawHandler] Error: %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable/1000, LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable/1000))
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// if no amount is entered, and if only one amount is possible, we use it
|
||||
if amount_err != nil && LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable == LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable {
|
||||
amount = int64(LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable / 1000)
|
||||
amount_err = nil
|
||||
}
|
||||
|
||||
// set also amount in the state of the user
|
||||
LnurlWithdrawState.Amount = amount * 1000 // save as mSat
|
||||
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(LnurlWithdrawState.Set(LnurlWithdrawState, bot.Bunt))
|
||||
|
||||
// now we actualy check whether the amount was in the command and if not, ask for it
|
||||
if amount_err != nil || amount < 1 {
|
||||
// // no amount was entered, set user state and ask for amount
|
||||
bot.askForAmount(ctx, id, "LnurlWithdrawState", LnurlWithdrawState.LNURLWithdrawResponse.MinWithdrawable, LnurlWithdrawState.LNURLWithdrawResponse.MaxWithdrawable, m.Text)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// We need to save the pay state in the user state so we can load the payment in the next handler
|
||||
paramsJson, err := json.Marshal(LnurlWithdrawState)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandler] Error: %s", err.Error())
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
|
||||
// directly go to confirm
|
||||
return bot.lnurlWithdrawHandlerWithdraw(ctx, m)
|
||||
}
|
||||
|
||||
// lnurlWithdrawHandlerWithdraw is invoked when the user has delivered an amount and is ready to pay
|
||||
func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
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 ctx, fmt.Errorf("wrong state key")
|
||||
}
|
||||
|
||||
// read the enter amount state from user.StateData
|
||||
var enterAmountData EnterAmountStateData
|
||||
err := json.Unmarshal([]byte(user.StateData), &enterAmountData)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// use the enter amount state of the user to load the LNURL payment state
|
||||
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(enterAmountData.ID))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
var lnurlWithdrawState *LnurlWithdrawState
|
||||
switch fn.(type) {
|
||||
case *LnurlWithdrawState:
|
||||
lnurlWithdrawState = fn.(*LnurlWithdrawState)
|
||||
default:
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] invalid type")
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, fmt.Errorf("invalid type")
|
||||
}
|
||||
|
||||
confirmText := fmt.Sprintf(Translate(ctx, "confirmLnurlWithdrawMessage"), lnurlWithdrawState.Amount/1000)
|
||||
if len(lnurlWithdrawState.LNURLWithdrawResponse.DefaultDescription) > 0 {
|
||||
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(lnurlWithdrawState.LNURLWithdrawResponse.DefaultDescription))
|
||||
}
|
||||
lnurlWithdrawState.Message = confirmText
|
||||
|
||||
// create inline buttons
|
||||
withdrawButton := paymentConfirmationMenu.Data(Translate(ctx, "withdrawButtonMessage"), "confirm_withdraw", lnurlWithdrawState.ID)
|
||||
btnCancelWithdraw := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_withdraw", lnurlWithdrawState.ID)
|
||||
|
||||
withdrawConfirmationMenu.Inline(
|
||||
withdrawConfirmationMenu.Row(
|
||||
withdrawButton,
|
||||
btnCancelWithdraw),
|
||||
)
|
||||
|
||||
bot.tryEditMessage(statusMsg, confirmText, withdrawConfirmationMenu)
|
||||
|
||||
// // add response to persistent struct
|
||||
// lnurlWithdrawState.LNURResponse = response2
|
||||
runtime.IgnoreError(lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// confirmPayHandler when user clicked pay on payment confirmation
|
||||
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 ctx, err
|
||||
}
|
||||
|
||||
var lnurlWithdrawState *LnurlWithdrawState
|
||||
switch fn.(type) {
|
||||
case *LnurlWithdrawState:
|
||||
lnurlWithdrawState = fn.(*LnurlWithdrawState)
|
||||
default:
|
||||
log.Errorf("[confirmWithdrawHandler] invalid type")
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
// onnly the correct user can press
|
||||
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
|
||||
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 ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
defer lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt)
|
||||
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
|
||||
// reset state immediately
|
||||
ResetUserState(user, bot)
|
||||
|
||||
// update button text
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlPreparingWithdraw"))
|
||||
|
||||
callbackUrl, err := url.Parse(lnurlWithdrawState.LNURLWithdrawResponse.Callback)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// generate an invoice and add the pr to the request
|
||||
// generate invoice
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: int64(lnurlWithdrawState.Amount) / 1000,
|
||||
Memo: "Withdraw",
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[lnurlWithdrawHandlerWithdraw] Could not create an invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
lnurlWithdrawState.Invoice = invoice
|
||||
|
||||
qs := callbackUrl.Query()
|
||||
// add amount to query string
|
||||
qs.Set("pr", invoice.PaymentRequest)
|
||||
qs.Set("k1", lnurlWithdrawState.LNURLWithdrawResponse.K1)
|
||||
callbackUrl.RawQuery = qs.Encode()
|
||||
|
||||
// lnurlWithdrawState loaded
|
||||
client, err := bot.GetHttpClient()
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] Error: %s", err.Error())
|
||||
// bot.trySendMessage(c.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "errorTryLaterMessage"))
|
||||
return 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 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 ctx, err
|
||||
}
|
||||
|
||||
// parse the response
|
||||
var response2 lnurl.LNURLResponse
|
||||
json.Unmarshal(body, &response2)
|
||||
if response2.Status == "OK" {
|
||||
// update button text
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawSuccess"))
|
||||
|
||||
} else {
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] LNURLWithdraw failed.")
|
||||
// update button text
|
||||
bot.editSingleButton(ctx, c.Message, lnurlWithdrawState.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawFailed"))
|
||||
return ctx, errors.New(errors.UnknownError, fmt.Errorf("LNURLWithdraw failed"))
|
||||
}
|
||||
|
||||
// add response to persistent struct
|
||||
lnurlWithdrawState.LNURResponse = response2
|
||||
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) (context.Context, error) {
|
||||
// reset state immediately
|
||||
user := LoadUser(ctx)
|
||||
ResetUserState(user, bot)
|
||||
tx := &LnurlWithdrawState{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelWithdrawHandler] Error: %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
var lnurlWithdrawState *LnurlWithdrawState
|
||||
switch fn.(type) {
|
||||
case *LnurlWithdrawState:
|
||||
lnurlWithdrawState = fn.(*LnurlWithdrawState)
|
||||
default:
|
||||
log.Errorf("[cancelWithdrawHandler] invalid type")
|
||||
}
|
||||
// onnly the correct user can press
|
||||
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawCancelled"), &tb.ReplyMarkup{})
|
||||
return ctx, lnurlWithdrawState.Inactivate(lnurlWithdrawState, bot.Bunt)
|
||||
}
|
||||
+181
-119
@@ -3,22 +3,21 @@ 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"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
lnurl "github.com/fiatjaf/go-lnurl"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
"github.com/tidwall/gjson"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot *TipBot) GetHttpClient() (*http.Client, error) {
|
||||
@@ -37,93 +36,49 @@ func (bot TipBot) cancelLnUrlHandler(c *tb.Callback) {
|
||||
}
|
||||
|
||||
// lnurlHandler is invoked on /lnurl command
|
||||
func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) {
|
||||
// commands:
|
||||
// /lnurl
|
||||
// /lnurl <LNURL>
|
||||
// or /lnurl <amount> <LNURL>
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
return
|
||||
}
|
||||
log.Infof("[lnurlHandler] %s", m.Text)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
|
||||
// if only /lnurl is entered, show the lnurl of the user
|
||||
if m.Text == "/lnurl" {
|
||||
return bot.lnurlReceiveHandler(ctx, m)
|
||||
}
|
||||
statusMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "lnurlResolvingUrlMessage"))
|
||||
|
||||
var lnurlSplit string
|
||||
split := strings.Split(m.Text, " ")
|
||||
if _, err := decodeAmountFromCommand(m.Text); err == nil {
|
||||
// command is /lnurl 123 <LNURL> [memo]
|
||||
if len(split) > 2 {
|
||||
lnurlSplit = split[2]
|
||||
}
|
||||
} else if len(split) > 1 {
|
||||
lnurlSplit = split[1]
|
||||
} else {
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "Could not parse command."))
|
||||
log.Warnln("[/lnurl] Could not parse command.")
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
bot.lnurlReceiveHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
// get rid of the URI prefix
|
||||
lnurlSplit = strings.TrimPrefix(lnurlSplit, "lightning:")
|
||||
|
||||
log.Debugf("[lnurlHandler] lnurlSplit: %s", lnurlSplit)
|
||||
// assume payment
|
||||
// HandleLNURL by fiatjaf/go-lnurl
|
||||
_, params, err := bot.HandleLNURL(lnurlSplit)
|
||||
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlResolvingUrlMessage"))
|
||||
_, params, err := bot.HandleLNURL(m.Text)
|
||||
if err != nil {
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "LNURL error."))
|
||||
// bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
log.Warnf("[HandleLNURL] Error: %s", err.Error())
|
||||
return ctx, err
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), "could not resolve LNURL."))
|
||||
log.Errorln(err)
|
||||
return
|
||||
}
|
||||
switch params.(type) {
|
||||
case lnurl.LNURLAuthParams:
|
||||
authParams := &LnurlAuthState{LNURLAuthParams: params.(lnurl.LNURLAuthParams)}
|
||||
log.Infof("[LNURL-auth] %s", authParams.LNURLAuthParams.Callback)
|
||||
case lnurl.LNURLPayResponse1:
|
||||
payParams := LnurlPayState{LNURLPayResponse1: params.(lnurl.LNURLPayResponse1)}
|
||||
log.Infof("[lnurlHandler] %s", payParams.LNURLPayResponse1.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)
|
||||
|
||||
// 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
|
||||
return bot.lnurlPayHandler(ctx, m, *payParams)
|
||||
|
||||
case lnurl.LNURLWithdrawResponse:
|
||||
withdrawParams := LnurlWithdrawState{LNURLWithdrawResponse: params.(lnurl.LNURLWithdrawResponse)}
|
||||
log.Infof("[LNURL-w] %s", withdrawParams.LNURLWithdrawResponse.Callback)
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
return bot.lnurlWithdrawHandler(ctx, m, withdrawParams)
|
||||
bot.lnurlPayHandler(ctx, m, payParams)
|
||||
return
|
||||
default:
|
||||
if err == nil {
|
||||
err = fmt.Errorf("invalid LNURL type")
|
||||
}
|
||||
log.Warnln(err)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
err := fmt.Errorf("invalid LNURL type.")
|
||||
log.Errorln(err)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) UserGetLightningAddress(user *lnbits.User) (string, error) {
|
||||
@@ -136,11 +91,18 @@ 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.AnonIDSha256), strings.ToLower(internal.Configuration.Bot.LNURLHostUrl.Hostname())), nil
|
||||
return fmt.Sprintf("%s@%s", fmt.Sprint(user.AnonID), strings.ToLower(internal.Configuration.Bot.LNURLHostUrl.Hostname())), nil
|
||||
}
|
||||
|
||||
func UserGetLNURL(user *lnbits.User) (string, error) {
|
||||
name := fmt.Sprint(user.UUID)
|
||||
// before: we used the username for the LNURL
|
||||
// name := strings.ToLower(strings.ToLower(user.Telegram.Username))
|
||||
// if len(name) == 0 {
|
||||
// name = fmt.Sprint(user.AnonID)
|
||||
// // return "", fmt.Errorf("user has no username.")
|
||||
// }
|
||||
// now: use only the anon ID as LNURL
|
||||
name := fmt.Sprint(user.AnonID)
|
||||
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, name)
|
||||
log.Debugf("[lnurlReceiveHandler] %s's LNURL: %s", GetUserStr(user.Telegram), callback)
|
||||
|
||||
@@ -152,31 +114,152 @@ func UserGetLNURL(user *lnbits.User) (string, error) {
|
||||
}
|
||||
|
||||
// lnurlReceiveHandler outputs the LNURL of the user
|
||||
func (bot TipBot) lnurlReceiveHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
func (bot TipBot) lnurlReceiveHandler(ctx context.Context, m *tb.Message) {
|
||||
fromUser := LoadUser(ctx)
|
||||
lnurlEncode, err := UserGetLNURL(fromUser)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to get LNURL: %s", err.Error())
|
||||
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to get LNURL: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlNoUsernameMessage"))
|
||||
return ctx, err
|
||||
bot.Telegram.Send(m.Sender, Translate(ctx, "lnurlNoUsernameMessage"))
|
||||
}
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(lnurlEncode, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to create QR code for LNURL: %s", err.Error())
|
||||
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to create QR code for LNURL: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlReceiveInfoText"))
|
||||
// send the lnurl QR code
|
||||
// send the lnurl data to user
|
||||
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
|
||||
func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
|
||||
// // lnurlEnterAmountHandler is invoked if the user didn't deliver an amount for the lnurl payment
|
||||
// func (bot *TipBot) lnurlEnterAmountHandler(ctx context.Context, m *tb.Message) {
|
||||
// user := LoadUser(ctx)
|
||||
// if user.Wallet == nil {
|
||||
// return
|
||||
// }
|
||||
|
||||
// if user.StateKey == lnbits.UserStateLNURLEnterAmount || user.StateKey == lnbits.UserEnterAmount {
|
||||
// a, err := strconv.Atoi(m.Text)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
|
||||
// ResetUserState(user, bot)
|
||||
// return
|
||||
// }
|
||||
// amount := int64(a)
|
||||
// var stateResponse LnurlPayState
|
||||
// err = json.Unmarshal([]byte(user.StateData), &stateResponse)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// ResetUserState(user, bot)
|
||||
// return
|
||||
// }
|
||||
// // amount not in allowed range from LNURL
|
||||
// if amount > (stateResponse.LNURLPayResponse1.MaxSendable/1000) || amount < (stateResponse.LNURLPayResponse1.MinSendable/1000) {
|
||||
// err = fmt.Errorf("amount not in range")
|
||||
// log.Errorln(err)
|
||||
// bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), stateResponse.LNURLPayResponse1.MinSendable/1000, stateResponse.LNURLPayResponse1.MaxSendable/1000))
|
||||
// ResetUserState(user, bot)
|
||||
// return
|
||||
// }
|
||||
// stateResponse.Amount = a
|
||||
// state, err := json.Marshal(stateResponse)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// ResetUserState(user, bot)
|
||||
// return
|
||||
// }
|
||||
// SetUserState(user, bot, lnbits.UserStateConfirmLNURLPay, string(state))
|
||||
// bot.lnurlPayHandler(ctx, m)
|
||||
// }
|
||||
// }
|
||||
|
||||
// // LnurlStateResponse saves the state of the user for an LNURL payment
|
||||
// type LnurlStateResponse struct {
|
||||
// lnurl.LNURLPayResponse1
|
||||
// Amount int `json:"amount"`
|
||||
// Comment string `json:"comment"`
|
||||
// }
|
||||
|
||||
// // lnurlPayHandler is invoked when the user has delivered an amount and is ready to pay
|
||||
// func (bot *TipBot) lnurlPayHandler(ctx context.Context, c *tb.Message) {
|
||||
// msg := bot.trySendMessage(c.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
|
||||
// user := LoadUser(ctx)
|
||||
// if user.Wallet == nil {
|
||||
// return
|
||||
// }
|
||||
|
||||
// if user.StateKey == lnbits.UserStateConfirmLNURLPay {
|
||||
// client, err := getHttpClient()
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// // bot.trySendMessage(c.Sender, err.Error())
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// return
|
||||
// }
|
||||
// var stateResponse LnurlStateResponse
|
||||
// err = json.Unmarshal([]byte(user.StateData), &stateResponse)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// // bot.trySendMessage(c.Sender, err.Error())
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// return
|
||||
// }
|
||||
// callbackUrl, err := url.Parse(stateResponse.Callback)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// // bot.trySendMessage(c.Sender, err.Error())
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// return
|
||||
// }
|
||||
// qs := callbackUrl.Query()
|
||||
// // add amount to query string
|
||||
// qs.Set("amount", strconv.Itoa(stateResponse.Amount*1000))
|
||||
// // add comment to query string
|
||||
// if len(stateResponse.Comment) > 0 {
|
||||
// qs.Set("comment", stateResponse.Comment)
|
||||
// }
|
||||
|
||||
// callbackUrl.RawQuery = qs.Encode()
|
||||
|
||||
// res, err := client.Get(callbackUrl.String())
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// // bot.trySendMessage(c.Sender, err.Error())
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// return
|
||||
// }
|
||||
// var response2 lnurl.LNURLPayResponse2
|
||||
// body, err := ioutil.ReadAll(res.Body)
|
||||
// if err != nil {
|
||||
// log.Errorln(err)
|
||||
// // bot.trySendMessage(c.Sender, err.Error())
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
|
||||
// return
|
||||
// }
|
||||
// json.Unmarshal(body, &response2)
|
||||
|
||||
// if len(response2.PR) < 1 {
|
||||
// error_reason := "Could not receive invoice."
|
||||
// if len(response2.Reason) > 0 {
|
||||
// error_reason = response2.Reason
|
||||
// }
|
||||
// bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
|
||||
// return
|
||||
// }
|
||||
// bot.Telegram.Delete(msg)
|
||||
// c.Text = fmt.Sprintf("/pay %s", response2.PR)
|
||||
// bot.payHandler(ctx, c)
|
||||
// }
|
||||
// }
|
||||
|
||||
// from https://github.com/fiatjaf/go-lnurl
|
||||
func (bot *TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
|
||||
var err error
|
||||
var rawurl string
|
||||
|
||||
@@ -190,24 +273,13 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
}
|
||||
} else if strings.HasPrefix(rawlnurl, "http") {
|
||||
rawurl = rawlnurl
|
||||
} else if strings.HasPrefix(rawlnurl, "lnurlp://") ||
|
||||
strings.HasPrefix(rawlnurl, "lnurlw://") ||
|
||||
strings.HasPrefix(rawlnurl, "lnurla://") ||
|
||||
strings.HasPrefix(rawlnurl, "keyauth://") {
|
||||
|
||||
scheme := "https:"
|
||||
if strings.Contains(rawurl, ".onion/") || strings.HasSuffix(rawurl, ".onion") {
|
||||
scheme = "http:"
|
||||
}
|
||||
location := strings.SplitN(rawlnurl, ":", 2)[1]
|
||||
rawurl = scheme + location
|
||||
} else {
|
||||
lnurl_str, ok := lnurl.FindLNURLInText(rawlnurl)
|
||||
foundUrl, ok := lnurl.FindLNURLInText(rawlnurl)
|
||||
if !ok {
|
||||
return "", nil,
|
||||
fmt.Errorf("invalid bech32-encoded lnurl: " + rawlnurl)
|
||||
errors.New("invalid bech32-encoded lnurl: " + rawlnurl)
|
||||
}
|
||||
rawurl, err = lnurl.LNURLDecode(lnurl_str)
|
||||
rawurl, err = lnurl.LNURLDecode(foundUrl)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
@@ -218,24 +290,17 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
return rawurl, nil, err
|
||||
}
|
||||
|
||||
query := parsed.Query()
|
||||
// query := parsed.Query()
|
||||
|
||||
switch query.Get("tag") {
|
||||
case "login":
|
||||
value, err := lnurl.HandleAuth(rawurl, parsed, query)
|
||||
return rawurl, value, err
|
||||
case "withdrawRequest":
|
||||
if value, ok := lnurl.HandleFastWithdraw(query); ok {
|
||||
return rawurl, value, nil
|
||||
}
|
||||
}
|
||||
|
||||
// // original withouth proxy
|
||||
// resp, err := http.Get(rawurl)
|
||||
// if err != nil {
|
||||
// return rawurl, nil, err
|
||||
// switch query.Get("tag") {
|
||||
// case "login":
|
||||
// value, err := lnurl.HandleAuth(rawurl, parsed, query)
|
||||
// return rawurl, value, err
|
||||
// case "withdrawRequest":
|
||||
// if value, ok := lnurl.HandleFastWithdraw(query); ok {
|
||||
// return rawurl, value, nil
|
||||
// }
|
||||
// }
|
||||
|
||||
client, err := bot.GetHttpClient()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
@@ -244,9 +309,6 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
if err != nil {
|
||||
return rawurl, nil, err
|
||||
}
|
||||
if resp.StatusCode >= 300 {
|
||||
return rawurl, nil, fmt.Errorf("HTTP error: " + resp.Status)
|
||||
}
|
||||
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
@@ -263,16 +325,16 @@ func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error
|
||||
}
|
||||
|
||||
switch j.Get("tag").String() {
|
||||
case "withdrawRequest":
|
||||
value, err := lnurl.HandleWithdraw(b)
|
||||
return rawurl, value, err
|
||||
// case "withdrawRequest":
|
||||
// value, err := lnurl.HandleWithdraw(j)
|
||||
// return rawurl, value, err
|
||||
case "payRequest":
|
||||
value, err := lnurl.HandlePay(b)
|
||||
value, err := lnurl.HandlePay(j)
|
||||
return rawurl, value, err
|
||||
// case "channelRequest":
|
||||
// value, err := lnurl.HandleChannel(b)
|
||||
// value, err := lnurl.HandleChannel(j)
|
||||
// return rawurl, value, err
|
||||
default:
|
||||
return rawurl, nil, fmt.Errorf("Unkown LNURL response.")
|
||||
return rawurl, nil, errors.New("unknown response tag " + j.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
|
||||
+56
-68
@@ -5,19 +5,14 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
decodepay "github.com/fiatjaf/ln-decodepay"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -35,7 +30,7 @@ func helpPayInvoiceUsage(ctx context.Context, errormsg string) string {
|
||||
}
|
||||
|
||||
type PayData struct {
|
||||
*storage.Base
|
||||
*transaction.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
Invoice string `json:"invoice"`
|
||||
Hash string `json:"hash"`
|
||||
@@ -48,26 +43,26 @@ type PayData struct {
|
||||
}
|
||||
|
||||
// payHandler invoked on "/pay lnbc..." command
|
||||
func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
if len(strings.Split(m.Text, " ")) < 2 {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, ""))
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
return
|
||||
}
|
||||
userStr := GetUserStr(m.Sender)
|
||||
paymentRequest, err := getArgumentFromCommand(m.Text, 1)
|
||||
if err != nil {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not getArgumentFromCommand: %s", err.Error())
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not getArgumentFromCommand: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, errors.New(errors.InvalidSyntaxError, err)
|
||||
return
|
||||
}
|
||||
paymentRequest = strings.ToLower(paymentRequest)
|
||||
// get rid of the URI prefix
|
||||
@@ -77,34 +72,36 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) (context.Conte
|
||||
bolt11, err := decodepay.Decodepay(paymentRequest)
|
||||
if err != nil {
|
||||
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err.Error())
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, errors.New(errors.InvalidSyntaxError, err)
|
||||
return
|
||||
}
|
||||
amount := int64(bolt11.MSatoshi / 1000)
|
||||
amount := int(bolt11.MSatoshi / 1000)
|
||||
|
||||
if amount <= 0 {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "invoiceNoAmountMessage"))
|
||||
errmsg := fmt.Sprint("[/pay] Error: invoice without amount")
|
||||
log.Warnln(errmsg)
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
return
|
||||
}
|
||||
|
||||
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
// check user balance first
|
||||
balance, err := bot.GetUserBalance(user)
|
||||
if err != nil {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err.Error())
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, errors.New(errors.GetBalanceError, err)
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
if amount > balance {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "insufficientFundsMessage"), balance, amount))
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "insufficientFundsMessage"), balance, amount))
|
||||
return
|
||||
}
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
// send warning that the invoice might fail due to missing fee reserve
|
||||
if float64(amount) > float64(balance)*0.99 {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "feeReserveMessage"))
|
||||
@@ -115,23 +112,25 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) (context.Conte
|
||||
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(bolt11.Description))
|
||||
}
|
||||
|
||||
log.Infof("[/pay] Invoice entered. User: %s, amount: %d sat.", userStr, amount)
|
||||
log.Printf("[/pay] User: %s, amount: %d sat.", userStr, amount)
|
||||
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("pay-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
|
||||
|
||||
// // // create inline buttons
|
||||
payButton := paymentConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "confirm_pay", id)
|
||||
cancelButton := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_pay", id)
|
||||
payButton := paymentConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "confirm_pay")
|
||||
cancelButton := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_pay")
|
||||
payButton.Data = id
|
||||
cancelButton.Data = id
|
||||
|
||||
paymentConfirmationMenu.Inline(
|
||||
paymentConfirmationMenu.Row(
|
||||
payButton,
|
||||
cancelButton),
|
||||
)
|
||||
payMessage := bot.trySendMessageEditable(m.Chat, confirmText, paymentConfirmationMenu)
|
||||
payData := &PayData{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
payMessage := bot.trySendMessage(m.Chat, confirmText, paymentConfirmationMenu)
|
||||
payData := PayData{
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
From: user,
|
||||
Invoice: paymentRequest,
|
||||
Amount: int64(amount),
|
||||
@@ -144,33 +143,38 @@ func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) (context.Conte
|
||||
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) (context.Context, error) {
|
||||
tx := &PayData{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &PayData{Base: transaction.New(transaction.ID(c.Data))}
|
||||
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
|
||||
log.Errorf("[confirmPayHandler] %s", err)
|
||||
return
|
||||
}
|
||||
payData := sn.(*PayData)
|
||||
|
||||
// onnly the correct user can press
|
||||
if payData.From.Telegram.ID != c.Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
return
|
||||
}
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
err = payData.Lock(payData, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err)
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
|
||||
return
|
||||
}
|
||||
if !payData.Active {
|
||||
log.Errorf("[confirmPayHandler] send not active anymore")
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
return
|
||||
}
|
||||
defer payData.Set(payData, bot.Bunt)
|
||||
defer payData.Release(payData, bot.Bunt)
|
||||
|
||||
// remove buttons from confirmation message
|
||||
// bot.tryEditMessage(c.Message, MarkdownEscape(payData.Message), &tb.ReplyMarkup{})
|
||||
@@ -178,7 +182,7 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) (conte
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
|
||||
invoiceString := payData.Invoice
|
||||
@@ -198,8 +202,6 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) (conte
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
log.Infof("[/pay] Attempting %s's invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
|
||||
// pay invoice
|
||||
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoiceString}, bot.Client)
|
||||
if err != nil {
|
||||
@@ -212,55 +214,41 @@ func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) (conte
|
||||
// }
|
||||
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), str.MarkdownEscape(err.Error())), &tb.ReplyMarkup{})
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
payData.Hash = invoice.PaymentHash
|
||||
|
||||
// do balance check for keyboard update
|
||||
_, err = bot.GetUserBalance(user)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", userStr)
|
||||
log.Errorln(errmsg)
|
||||
}
|
||||
payData.InTransaction = false
|
||||
|
||||
if c.Message.Private() {
|
||||
// if the command was invoked in private chat
|
||||
// the edit below was cool, but we need to pop up the keyboard again
|
||||
// bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
bot.trySendMessage(c.Sender, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
|
||||
} else {
|
||||
// if the command was invoked in group chat
|
||||
bot.trySendMessage(c.Sender, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
|
||||
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePublicPaidMessage"), userStr), &tb.ReplyMarkup{})
|
||||
}
|
||||
log.Infof("[⚡️ pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
|
||||
return ctx, nil
|
||||
log.Printf("[pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
|
||||
return
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot *TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
|
||||
func (bot *TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) {
|
||||
// reset state immediately
|
||||
user := LoadUser(ctx)
|
||||
ResetUserState(user, bot)
|
||||
tx := &PayData{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
tx := &PayData{Base: transaction.New(transaction.ID(c.Data))}
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
log.Errorf("[cancelPaymentHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
payData := sn.(*PayData)
|
||||
// onnly the correct user can press
|
||||
if payData.From.Telegram.ID != c.Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
return
|
||||
}
|
||||
// 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)
|
||||
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"), &tb.ReplyMarkup{})
|
||||
payData.InTransaction = false
|
||||
payData.Inactivate(payData, bot.Bunt)
|
||||
}
|
||||
|
||||
+14
-95
@@ -1,23 +1,17 @@
|
||||
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"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
// TryRecognizeInvoiceFromQrCode will try to read an invoice string from a qr code and invoke the payment handler.
|
||||
@@ -40,117 +34,42 @@ 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) (context.Context, error) {
|
||||
func (bot TipBot) photoHandler(ctx context.Context, m *tb.Message) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
return
|
||||
}
|
||||
if m.Photo == nil {
|
||||
return ctx, errors.Create(errors.NoPhotoError)
|
||||
}
|
||||
user := LoadUser(ctx)
|
||||
if c := stateCallbackMessage[user.StateKey]; c != nil {
|
||||
ctx, err := c(ctx, m)
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
// get file reader closer from Telegram api
|
||||
reader, err := bot.Telegram.GetFile(m.Photo.MediaFile())
|
||||
if err != nil {
|
||||
log.Errorf("[photoHandler] getfile error: %v\n", err.Error())
|
||||
return ctx, err
|
||||
log.Errorf("[photoHandler] getfile error: %v\n", err)
|
||||
return
|
||||
}
|
||||
// decode to jpeg image
|
||||
img, err := jpeg.Decode(reader)
|
||||
if err != nil {
|
||||
log.Errorf("[photoHandler] image.Decode error: %v\n", err.Error())
|
||||
return ctx, err
|
||||
log.Errorf("[photoHandler] image.Decode error: %v\n", err)
|
||||
return
|
||||
}
|
||||
data, err := TryRecognizeQrCode(img)
|
||||
if err != nil {
|
||||
log.Errorf("[photoHandler] tryRecognizeQrCodes error: %v\n", err.Error())
|
||||
log.Errorf("[photoHandler] tryRecognizeQrCodes error: %v\n", err)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "photoQrNotRecognizedMessage"))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
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())
|
||||
return bot.payHandler(ctx, m)
|
||||
bot.payHandler(ctx, m)
|
||||
return
|
||||
} else if lightning.IsLnurl(data.String()) {
|
||||
m.Text = fmt.Sprintf("/lnurl %s", data.String())
|
||||
return bot.lnurlHandler(ctx, m)
|
||||
bot.lnurlHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
+59
-122
@@ -6,19 +6,14 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -44,9 +39,9 @@ func (bot *TipBot) SendCheckSyntax(ctx context.Context, m *tb.Message) (bool, st
|
||||
}
|
||||
|
||||
type SendData struct {
|
||||
*storage.Base
|
||||
*transaction.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
ToTelegramId int64 `json:"to_telegram_id"`
|
||||
ToTelegramId int `json:"to_telegram_id"`
|
||||
ToTelegramUser string `json:"to_telegram_user"`
|
||||
Memo string `json:"memo"`
|
||||
Message string `json:"message"`
|
||||
@@ -55,11 +50,11 @@ type SendData struct {
|
||||
}
|
||||
|
||||
// sendHandler invoked on "/send 123 @user" command
|
||||
func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
return
|
||||
}
|
||||
|
||||
// reset state immediately
|
||||
@@ -69,15 +64,15 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Cont
|
||||
|
||||
// If the send is a reply, then trigger /tip handler
|
||||
if m.IsReply() && m.Chat.Type != tb.ChatPrivate {
|
||||
return bot.tipHandler(ctx, m)
|
||||
|
||||
bot.tipHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
// if ok, errstr := bot.SendCheckSyntax(ctx, m); !ok {
|
||||
// bot.trySendMessage(m.Sender, helpSendUsage(ctx, errstr))
|
||||
// NewMessage(m, WithDuration(0, bot))
|
||||
// return
|
||||
// }
|
||||
if ok, errstr := bot.SendCheckSyntax(ctx, m); !ok {
|
||||
bot.trySendMessage(m.Sender, helpSendUsage(ctx, errstr))
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
return
|
||||
}
|
||||
|
||||
// get send amount, returns 0 if no amount is given
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
@@ -94,27 +89,21 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Cont
|
||||
if err == nil {
|
||||
if lightning.IsLightningAddress(arg) {
|
||||
// lightning address, send to that address
|
||||
ctx, err = bot.sendToLightningAddress(ctx, m, arg, amount)
|
||||
err = bot.sendToLightningAddress(ctx, m, arg, amount)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// is a user given?
|
||||
arg, err = getArgumentFromCommand(m.Text, 1)
|
||||
if err != nil && m.Chat.Type == tb.ChatPrivate {
|
||||
_, err = bot.askForUser(ctx, "", "CreateSendState", m.Text)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// is an amount given?
|
||||
// todo: this error might have been overwritten by the functions above
|
||||
// we should only check for a valid amount here, instead of error and amount
|
||||
amount, err = decodeAmountFromCommand(m.Text)
|
||||
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
|
||||
_, err = bot.askForAmount(ctx, "", "CreateSendState", 0, 0, m.Text)
|
||||
return ctx, err
|
||||
bot.askForAmount(ctx, "", "CreateSendState", 0, 0, m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// ASSUME INTERNAL SEND TO TELEGRAM USER
|
||||
@@ -124,7 +113,7 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Cont
|
||||
// immediately delete if the amount is bullshit
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpSendUsage(ctx, Translate(ctx, "sendValidAmountMessage")))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
|
||||
// SEND COMMAND IS VALID
|
||||
@@ -142,31 +131,22 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Cont
|
||||
toUserStrWithoutAt, err = getArgumentFromCommand(m.Text, 2)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
toUserStrWithoutAt = strings.TrimPrefix(toUserStrWithoutAt, "@")
|
||||
toUserStrMention = "@" + toUserStrWithoutAt
|
||||
toUserStrWithoutAt = strings.TrimPrefix(toUserStrWithoutAt, "@")
|
||||
}
|
||||
|
||||
err = bot.parseCmdDonHandler(ctx, m)
|
||||
if err == nil {
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
return
|
||||
}
|
||||
|
||||
toUserDb, err := GetUserByTelegramUsername(toUserStrWithoutAt, *bot)
|
||||
if err != nil {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
// cut username if it's too long
|
||||
if len(toUserStrMention) > 100 {
|
||||
toUserStrMention = toUserStrMention[:100]
|
||||
}
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), str.MarkdownEscape(toUserStrMention)))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
if user.ID == toUserDb.ID {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "sendYourselfMessage"))
|
||||
return ctx, errors.Create(errors.SelfPaymentError)
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), toUserStrMention))
|
||||
return
|
||||
}
|
||||
|
||||
// entire text of the inline object
|
||||
@@ -176,9 +156,9 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Cont
|
||||
}
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("send-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
|
||||
sendData := &SendData{
|
||||
sendData := SendData{
|
||||
From: user,
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Base: transaction.New(transaction.ID(id)),
|
||||
Amount: int64(amount),
|
||||
ToTelegramId: toUserDb.Telegram.ID,
|
||||
ToTelegramUser: toUserStrWithoutAt,
|
||||
@@ -194,7 +174,7 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Cont
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
log.Printf("[/send] Error: %s\n", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprint(Translate(ctx, "errorTryLaterMessage")))
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
// save the send data to the Database
|
||||
// log.Debug(sendData)
|
||||
@@ -214,70 +194,34 @@ func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Cont
|
||||
} 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) (context.Context, error) {
|
||||
tx := &SendData{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &SendData{Base: transaction.New(transaction.ID(c.Data))}
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
log.Errorf("[acceptSendHandler] %s", err)
|
||||
return
|
||||
}
|
||||
sendData := sn.(*SendData)
|
||||
// onnly the correct user can press
|
||||
if sendData.From.Telegram.ID != c.Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
return
|
||||
}
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
err = sendData.Lock(sendData, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err)
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
}
|
||||
if !sendData.Active {
|
||||
log.Errorf("[acceptSendHandler] send not active anymore")
|
||||
// bot.tryDeleteMessage(c.Message)
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
return
|
||||
}
|
||||
defer sendData.Set(sendData, bot.Bunt)
|
||||
defer sendData.Release(sendData, bot.Bunt)
|
||||
|
||||
// // remove buttons from confirmation message
|
||||
// bot.tryEditMessage(c.Message, MarkdownEscape(sendData.Message), &tb.ReplyMarkup{})
|
||||
@@ -298,7 +242,7 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) (cont
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return ctx, err
|
||||
return
|
||||
}
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
@@ -306,30 +250,27 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) (cont
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
|
||||
transactionMemo := fmt.Sprintf("Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
t := NewTransaction(bot, from, to, amount, TransactionType("send"))
|
||||
t := NewTransaction(bot, from, to, int(amount), TransactionType("send"))
|
||||
t.Memo = transactionMemo
|
||||
|
||||
success, err := t.Send()
|
||||
if !success || err != nil {
|
||||
// bot.trySendMessage(c.Sender, sendErrorMessage)
|
||||
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err.Error())
|
||||
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err)
|
||||
log.Errorln(errmsg)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(sendData.LanguageCode, "sendErrorMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
bot.tryEditMessage(c.Message, fmt.Sprintf("%s %s", i18n.Translate(sendData.LanguageCode, "sendErrorMessage"), err), &tb.ReplyMarkup{})
|
||||
return
|
||||
}
|
||||
sendData.Inactivate(sendData, bot.Bunt)
|
||||
|
||||
log.Infof("[💸 send] Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
log.Infof("[send] Transaction sent from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
|
||||
// notify to user
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
|
||||
// bot.trySendMessage(from.Telegram, fmt.Sprintf(Translate(ctx, "sendSentMessage"), amount, toUserStrMd))
|
||||
if c.Message.Private() {
|
||||
// if the command was invoked in private chat
|
||||
// the edit below was cool, but we need to get rid of the replymarkup inline keyboard thingy for the main menu to pop up
|
||||
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd), &tb.ReplyMarkup{})
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
bot.trySendMessage(c.Sender, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
|
||||
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd), &tb.ReplyMarkup{})
|
||||
} else {
|
||||
// if the command was invoked in group chat
|
||||
bot.trySendMessage(c.Sender, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
|
||||
@@ -340,31 +281,27 @@ func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) (cont
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(sendMemo)))
|
||||
}
|
||||
|
||||
return ctx, nil
|
||||
return
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
|
||||
func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
// reset state immediately
|
||||
user := LoadUser(ctx)
|
||||
ResetUserState(user, bot)
|
||||
tx := &SendData{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
tx := &SendData{Base: transaction.New(transaction.ID(c.Data))}
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
log.Errorf("[acceptSendHandler] %s", err)
|
||||
return
|
||||
}
|
||||
|
||||
sendData := sn.(*SendData)
|
||||
// onnly the correct user can press
|
||||
if sendData.From.Telegram.ID != c.Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
return
|
||||
}
|
||||
// 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"))
|
||||
// remove buttons from confirmation message
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(sendData.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
|
||||
sendData.InTransaction = false
|
||||
sendData.Inactivate(sendData, bot.Bunt)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,286 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot TipBot) shopsMainMenu(ctx context.Context, shops *Shops) *tb.ReplyMarkup {
|
||||
browseShopButton := shopKeyboard.Data("🛍 Browse shops", "shops_browse", shops.ID)
|
||||
shopNewShopButton := shopKeyboard.Data("✅ New Shop", "shops_newshop", shops.ID)
|
||||
shopSettingsButton := shopKeyboard.Data("⚙️ Settings", "shops_settings", shops.ID)
|
||||
user := LoadUser(ctx)
|
||||
|
||||
buttons := []tb.Row{}
|
||||
if len(shops.Shops) > 0 {
|
||||
buttons = append(buttons, shopKeyboard.Row(browseShopButton))
|
||||
}
|
||||
if user.Telegram.ID == shops.Owner.Telegram.ID {
|
||||
buttons = append(buttons, shopKeyboard.Row(shopNewShopButton, shopSettingsButton))
|
||||
}
|
||||
shopKeyboard.Inline(
|
||||
buttons...,
|
||||
)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
func (bot TipBot) shopsSettingsMenu(ctx context.Context, shops *Shops) *tb.ReplyMarkup {
|
||||
shopShopsButton := shopKeyboard.Data("⬅️ Back", "shops_shops", shops.ID)
|
||||
shopLinkShopButton := shopKeyboard.Data("🔗 Shop links", "shops_linkshop", shops.ID)
|
||||
shopRenameShopButton := shopKeyboard.Data("⌨️ Rename a shop", "shops_renameshop", shops.ID)
|
||||
shopDeleteShopButton := shopKeyboard.Data("🚫 Delete shops", "shops_deleteshop", shops.ID)
|
||||
shopDescriptionShopButton := shopKeyboard.Data("💬 Description", "shops_description", shops.ID)
|
||||
// // shopResetShopButton := shopKeyboard.Data("⚠️ Delete all shops", "shops_reset", shops.ID)
|
||||
// buttons := []tb.Row{
|
||||
// shopKeyboard.Row(shopLinkShopButton),
|
||||
// shopKeyboard.Row(shopDescriptionShopButton),
|
||||
// shopKeyboard.Row(shopRenameShopButton),
|
||||
// shopKeyboard.Row(shopDeleteShopButton),
|
||||
// // shopKeyboard.Row(shopResetShopButton),
|
||||
// shopKeyboard.Row(shopShopsButton),
|
||||
// }
|
||||
// shopKeyboard.Inline(
|
||||
// buttons...,
|
||||
// )
|
||||
|
||||
button := []tb.Btn{
|
||||
shopLinkShopButton,
|
||||
shopDescriptionShopButton,
|
||||
shopRenameShopButton,
|
||||
shopDeleteShopButton,
|
||||
shopShopsButton,
|
||||
}
|
||||
shopKeyboard.Inline(buttonWrapper(button, shopKeyboard, 2)...)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
// shopItemSettingsMenu builds the buttons of the item settings
|
||||
func (bot TipBot) shopItemSettingsMenu(ctx context.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
|
||||
shopItemPriceButton = shopKeyboard.Data("💯 Set price", "shop_itemprice", item.ID)
|
||||
shopItemDeleteButton = shopKeyboard.Data("🚫 Delete item", "shop_itemdelete", item.ID)
|
||||
shopItemTitleButton = shopKeyboard.Data("⌨️ Set title", "shop_itemtitle", item.ID)
|
||||
shopItemAddFileButton = shopKeyboard.Data("💾 Add files ...", "shop_itemaddfile", item.ID)
|
||||
shopItemSettingsBackButton = shopKeyboard.Data("⬅️ Back", "shop_itemsettingsback", item.ID)
|
||||
user := LoadUser(ctx)
|
||||
buttons := []tb.Row{}
|
||||
if user.Telegram.ID == shop.Owner.Telegram.ID {
|
||||
buttons = append(buttons, shopKeyboard.Row(shopItemDeleteButton, shopItemSettingsBackButton))
|
||||
buttons = append(buttons, shopKeyboard.Row(shopItemTitleButton, shopItemPriceButton))
|
||||
buttons = append(buttons, shopKeyboard.Row(shopItemAddFileButton))
|
||||
}
|
||||
shopKeyboard.Inline(
|
||||
buttons...,
|
||||
)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
// shopItemConfirmBuyMenu builds the buttons to confirm a purchase
|
||||
func (bot TipBot) shopItemConfirmBuyMenu(ctx context.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
|
||||
shopItemBuyButton = shopKeyboard.Data(fmt.Sprintf("💸 Pay %d sat", item.Price), "shop_itembuy", item.ID)
|
||||
shopItemCancelBuyButton = shopKeyboard.Data("⬅️ Back", "shop_itemcancelbuy", item.ID)
|
||||
buttons := []tb.Row{}
|
||||
buttons = append(buttons, shopKeyboard.Row(shopItemBuyButton))
|
||||
buttons = append(buttons, shopKeyboard.Row(shopItemCancelBuyButton))
|
||||
shopKeyboard.Inline(
|
||||
buttons...,
|
||||
)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
// shopMenu builds the buttons in the item browser
|
||||
func (bot TipBot) shopMenu(ctx context.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
|
||||
user := LoadUser(ctx)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
shopShopsButton := shopKeyboard.Data("⬅️ Back", "shops_shops", shop.ShopsID)
|
||||
shopAddItemButton = shopKeyboard.Data("✅ New item", "shop_additem", shop.ID)
|
||||
shopItemSettingsButton = shopKeyboard.Data("⚙️ Settings", "shop_itemsettings", item.ID)
|
||||
shopNextitemButton = shopKeyboard.Data(">", "shop_nextitem", shop.ID)
|
||||
shopPrevitemButton = shopKeyboard.Data("<", "shop_previtem", shop.ID)
|
||||
buyButtonText := "📩 Get"
|
||||
if item.Price > 0 {
|
||||
buyButtonText = fmt.Sprintf("Buy (%d sat)", item.Price)
|
||||
}
|
||||
shopBuyitemButton = shopKeyboard.Data(buyButtonText, "shop_buyitem", item.ID)
|
||||
|
||||
buttons := []tb.Row{}
|
||||
if user.Telegram.ID == shop.Owner.Telegram.ID {
|
||||
if len(shop.Items) == 0 {
|
||||
buttons = append(buttons, shopKeyboard.Row(shopAddItemButton))
|
||||
} else {
|
||||
buttons = append(buttons, shopKeyboard.Row(shopAddItemButton, shopItemSettingsButton))
|
||||
}
|
||||
}
|
||||
// publicButtons := []tb.Row{}
|
||||
if len(shop.Items) > 0 {
|
||||
if shopView.Page == len(shop.Items)-1 {
|
||||
// last page
|
||||
shopNextitemButton = shopKeyboard.Data("x", "shop_nextitem", shop.ID)
|
||||
}
|
||||
buttons = append(buttons, shopKeyboard.Row(shopPrevitemButton, shopBuyitemButton, shopNextitemButton))
|
||||
}
|
||||
buttons = append(buttons, shopKeyboard.Row(shopShopsButton))
|
||||
shopKeyboard.Inline(
|
||||
buttons...,
|
||||
)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
// makseShopSelectionButtons produces a list of all buttons with a uniqueString ID
|
||||
func (bot *TipBot) makseShopSelectionButtons(shops []*Shop, uniqueString string) []tb.Btn {
|
||||
var buttons []tb.Btn
|
||||
for _, shop := range shops {
|
||||
buttons = append(buttons, shopKeyboard.Data(shop.Title, uniqueString, shop.ID))
|
||||
}
|
||||
return buttons
|
||||
}
|
||||
|
||||
// -------------- ShopView --------------
|
||||
|
||||
// getUserShopview returns ShopView object from cache that holds information about the user's current browsing view
|
||||
func (bot *TipBot) getUserShopview(ctx context.Context, user *lnbits.User) (shopView ShopView, err error) {
|
||||
sv, err := bot.Cache.Get(fmt.Sprintf("shopview-%d", user.Telegram.ID))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
shopView = sv.(ShopView)
|
||||
return
|
||||
}
|
||||
func (bot *TipBot) shopViewDeleteAllStatusMsgs(ctx context.Context, user *lnbits.User) (shopView ShopView, err error) {
|
||||
mutex.Lock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
|
||||
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})
|
||||
return
|
||||
}
|
||||
|
||||
func deleteStatusMessages(messages []*tb.Message, bot *TipBot) {
|
||||
// delete all status messages from telegram
|
||||
for _, msg := range messages {
|
||||
bot.tryDeleteMessage(msg)
|
||||
}
|
||||
}
|
||||
|
||||
// sendStatusMessage adds a status message to the shopVoew.statusMessages
|
||||
// slide and sends a status message to the user.
|
||||
func (bot *TipBot) sendStatusMessage(ctx context.Context, to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
id := fmt.Sprintf("shopview-delete-%d", user.Telegram.ID)
|
||||
|
||||
// write into cache
|
||||
mutex.Lock(id)
|
||||
defer mutex.Unlock(id)
|
||||
shopView, err := bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
statusMsg := bot.trySendMessage(to, what, options...)
|
||||
shopView.StatusMessages = append(shopView.StatusMessages, statusMsg)
|
||||
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
|
||||
return statusMsg
|
||||
}
|
||||
|
||||
// sendStatusMessageAndDelete invokes sendStatusMessage and creates
|
||||
// a ticker to delete all status messages after 5 seconds.
|
||||
func (bot *TipBot) sendStatusMessageAndDelete(ctx context.Context, to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
id := fmt.Sprintf("shopview-delete-%d", user.Telegram.ID)
|
||||
statusMsg := bot.sendStatusMessage(ctx, to, what, options...)
|
||||
// kick off ticker to remove all messages
|
||||
ticker := runtime.GetTicker(id, runtime.WithDuration(5*time.Second))
|
||||
if !ticker.Started {
|
||||
ticker.Do(func() {
|
||||
bot.shopViewDeleteAllStatusMsgs(ctx, user)
|
||||
// removing ticker asap done
|
||||
runtime.RemoveTicker(id)
|
||||
})
|
||||
} else {
|
||||
ticker.ResetChan <- struct{}{}
|
||||
}
|
||||
return statusMsg
|
||||
}
|
||||
|
||||
// --------------- Shop ---------------
|
||||
|
||||
// initUserShops is a helper function for creating a Shops for the user in the database
|
||||
func (bot *TipBot) initUserShops(ctx context.Context, user *lnbits.User) (*Shops, error) {
|
||||
id := fmt.Sprintf("shops-%d", user.Telegram.ID)
|
||||
shops := &Shops{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Owner: user,
|
||||
Shops: []string{},
|
||||
MaxShops: MAX_SHOPS,
|
||||
}
|
||||
runtime.IgnoreError(shops.Set(shops, bot.ShopBunt))
|
||||
return shops, nil
|
||||
}
|
||||
|
||||
// getUserShops returns the Shops for the user
|
||||
func (bot *TipBot) getUserShops(ctx context.Context, user *lnbits.User) (*Shops, error) {
|
||||
tx := &Shops{Base: storage.New(storage.ID(fmt.Sprintf("shops-%d", user.Telegram.ID)))}
|
||||
sn, err := tx.Get(tx, bot.ShopBunt)
|
||||
if err != nil {
|
||||
log.Errorf("[getUserShops] User: %s (%d): %s", GetUserStr(user.Telegram), user.Telegram.ID, err)
|
||||
return &Shops{}, err
|
||||
}
|
||||
shops := sn.(*Shops)
|
||||
return shops, nil
|
||||
}
|
||||
|
||||
// addUserShop adds a new Shop to the Shops of a user
|
||||
func (bot *TipBot) addUserShop(ctx context.Context, user *lnbits.User) (*Shop, error) {
|
||||
shops, err := bot.getUserShops(ctx, user)
|
||||
if err != nil {
|
||||
return &Shop{}, err
|
||||
}
|
||||
shopId := fmt.Sprintf("shop-%s", RandStringRunes(10))
|
||||
shop := &Shop{
|
||||
Base: storage.New(storage.ID(shopId)),
|
||||
Title: fmt.Sprintf("Shop %d (%s)", len(shops.Shops)+1, shopId),
|
||||
Owner: user,
|
||||
Type: "photo",
|
||||
Items: make(map[string]ShopItem),
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
ShopsID: shops.ID,
|
||||
MaxItems: MAX_ITEMS_PER_SHOP,
|
||||
}
|
||||
runtime.IgnoreError(shop.Set(shop, bot.ShopBunt))
|
||||
shops.Shops = append(shops.Shops, shopId)
|
||||
runtime.IgnoreError(shops.Set(shops, bot.ShopBunt))
|
||||
return shop, nil
|
||||
}
|
||||
|
||||
// getShop returns the Shop of a given ID
|
||||
func (bot *TipBot) getShop(ctx context.Context, shopId string) (*Shop, error) {
|
||||
tx := &Shop{Base: storage.New(storage.ID(shopId))}
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
sn, err := tx.Get(tx, bot.ShopBunt)
|
||||
if err != nil {
|
||||
log.Errorf("[getShop] %s", err.Error())
|
||||
return &Shop{}, err
|
||||
}
|
||||
shop := sn.(*Shop)
|
||||
if shop.Owner == nil {
|
||||
return &Shop{}, fmt.Errorf("shop has no owner")
|
||||
}
|
||||
return shop, nil
|
||||
}
|
||||
+13
-21
@@ -2,37 +2,35 @@ package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func (bot TipBot) startHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
func (bot TipBot) startHandler(ctx context.Context, m *tb.Message) {
|
||||
if !m.Private() {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
return
|
||||
}
|
||||
// ATTENTION: DO NOT CALL ANY HANDLER BEFORE THE WALLET IS CREATED
|
||||
// WILL RESULT IN AN ENDLESS LOOP OTHERWISE
|
||||
// bot.helpHandler(m)
|
||||
log.Printf("[⭐️ /start] New user: %s (%d)\n", GetUserStr(m.Sender), m.Sender.ID)
|
||||
walletCreationMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "startSettingWalletMessage"))
|
||||
log.Printf("[/start] User: %s (%d)\n", m.Sender.Username, m.Sender.ID)
|
||||
walletCreationMsg, err := bot.Telegram.Send(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 ctx, err
|
||||
return
|
||||
}
|
||||
bot.tryDeleteMessage(walletCreationMsg)
|
||||
ctx = context.WithValue(ctx, "user", user)
|
||||
@@ -44,19 +42,17 @@ func (bot TipBot) startHandler(ctx context.Context, m *tb.Message) (context.Cont
|
||||
if len(m.Sender.Username) == 0 {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "startNoUsernameMessage"), tb.NoPreview)
|
||||
}
|
||||
return ctx, nil
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
|
||||
user, err := GetUser(tguser, bot)
|
||||
if stderrors.Is(err, gorm.ErrRecordNotFound) {
|
||||
if errors.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 {
|
||||
@@ -84,12 +80,12 @@ func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
|
||||
|
||||
func (bot TipBot) createWallet(user *lnbits.User) error {
|
||||
UserStr := GetUserStr(user.Telegram)
|
||||
u, err := bot.Client.CreateUserWithInitialWallet(strconv.FormatInt(user.Telegram.ID, 10),
|
||||
u, err := bot.Client.CreateUserWithInitialWallet(strconv.Itoa(user.Telegram.ID),
|
||||
fmt.Sprintf("%d (%s)", user.Telegram.ID, UserStr),
|
||||
internal.Configuration.Lnbits.AdminId,
|
||||
UserStr)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err.Error())
|
||||
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err)
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
@@ -98,21 +94,17 @@ func (bot TipBot) createWallet(user *lnbits.User) error {
|
||||
user.Name = u.Name
|
||||
wallet, err := bot.Client.Wallets(*user)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err.Error())
|
||||
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err)
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
user.Wallet = &wallet[0]
|
||||
|
||||
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
|
||||
user.AnonIDSha256 = str.AnonIdSha256(user)
|
||||
user.UUID = str.UUIDSha256(user)
|
||||
|
||||
user.Initialized = false
|
||||
user.CreatedAt = time.Now()
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err.Error())
|
||||
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err)
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type StateCallbackMessage map[lnbits.UserStateKey]func(ctx context.Context, m *tb.Message) (context.Context, error)
|
||||
|
||||
var stateCallbackMessage StateCallbackMessage
|
||||
|
||||
func initializeStateCallbackMessage(bot *TipBot) {
|
||||
stateCallbackMessage = StateCallbackMessage{
|
||||
lnbits.UserStateLNURLEnterAmount: bot.enterAmountHandler,
|
||||
lnbits.UserEnterAmount: bot.enterAmountHandler,
|
||||
lnbits.UserEnterUser: bot.enterUserHandler,
|
||||
lnbits.UserEnterShopTitle: bot.enterShopTitleHandler,
|
||||
lnbits.UserStateShopItemSendPhoto: bot.addShopItemPhoto,
|
||||
lnbits.UserStateShopItemSendPrice: bot.enterShopItemPriceHandler,
|
||||
lnbits.UserStateShopItemSendTitle: bot.enterShopItemTitleHandler,
|
||||
lnbits.UserStateShopItemSendItemFile: bot.addItemFileHandler,
|
||||
lnbits.UserEnterShopsDescription: bot.enterShopsDescriptionHandler,
|
||||
}
|
||||
}
|
||||
@@ -1,57 +1,18 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/rate"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
// getChatIdFromRecipient will parse the recipient to int64
|
||||
func (bot *TipBot) getChatIdFromRecipient(to tb.Recipient) (int64, error) {
|
||||
chatId, err := strconv.ParseInt(to.Recipient(), 10, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return chatId, nil
|
||||
}
|
||||
|
||||
func (bot TipBot) tryForwardMessage(to tb.Recipient, what tb.Editable, options ...interface{}) (msg *tb.Message) {
|
||||
rate.CheckLimit(to)
|
||||
// ChatId is used for the keyboard
|
||||
chatId, err := bot.getChatIdFromRecipient(to)
|
||||
if err != nil {
|
||||
log.Errorf("[tryForwardMessage] error converting message recipient to int64: %v", err)
|
||||
return
|
||||
}
|
||||
msg, err = bot.Telegram.Forward(to, what, bot.appendMainMenu(chatId, to, options)...)
|
||||
msg, err := bot.Telegram.Forward(to, what, options...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
func (bot TipBot) trySendMessage(to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
rate.CheckLimit(to)
|
||||
// ChatId is used for the keyboard
|
||||
chatId, err := bot.getChatIdFromRecipient(to)
|
||||
if err != nil {
|
||||
log.Errorf("[trySendMessage] error converting message recipient to int64: %v", err)
|
||||
return
|
||||
}
|
||||
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())
|
||||
}
|
||||
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())
|
||||
@@ -60,25 +21,15 @@ func (bot TipBot) trySendMessageEditable(to tb.Recipient, what interface{}, opti
|
||||
}
|
||||
|
||||
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)...)
|
||||
msg, err := bot.Telegram.Reply(to, what, options...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...interface{}) (msg *tb.Message, err error) {
|
||||
// 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()
|
||||
log.Tracef("[tryEditMessage] sig: %s, chatId: %d", sig, chatId)
|
||||
msg, err = bot.Telegram.Edit(to, what, options...)
|
||||
func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
msg, err := bot.Telegram.Edit(to, what, options...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
@@ -86,54 +37,8 @@ func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...in
|
||||
}
|
||||
|
||||
func (bot TipBot) tryDeleteMessage(msg tb.Editable) {
|
||||
if !allowedToPerformAction(bot, msg, isAdminAndCanDelete) {
|
||||
return
|
||||
}
|
||||
rate.CheckLimit(msg)
|
||||
err := bot.Telegram.Delete(msg)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
// allowedToPerformAction will check if bot is allowed to perform an action on the tb.Editable.
|
||||
// this function will persist the admins list in cache for 5 minutes.
|
||||
// if no admins list is found for this group, bot will always fetch a fresh list.
|
||||
func allowedToPerformAction(bot TipBot, editable tb.Editable, action func(members []tb.ChatMember, me *tb.User) bool) bool {
|
||||
switch editable.(type) {
|
||||
case *tb.Message:
|
||||
message := editable.(*tb.Message)
|
||||
if message.Sender.ID == bot.Telegram.Me.ID {
|
||||
break
|
||||
}
|
||||
chat := message.Chat
|
||||
if chat.Type == tb.ChatSuperGroup || chat.Type == tb.ChatGroup {
|
||||
admins, err := bot.Cache.Get(fmt.Sprintf("admins-%d", chat.ID))
|
||||
if err != nil {
|
||||
admins, err = bot.Telegram.AdminsOf(message.Chat)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
return false
|
||||
}
|
||||
bot.Cache.Set(fmt.Sprintf("admins-%d", chat.ID), admins, &store.Options{Expiration: 5 * time.Minute})
|
||||
}
|
||||
if action(admins.([]tb.ChatMember), bot.Telegram.Me) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// isAdminAndCanDelete will check if me is in members list and allowed to delete messages
|
||||
func isAdminAndCanDelete(members []tb.ChatMember, me *tb.User) bool {
|
||||
for _, admin := range members {
|
||||
if admin.User.ID == me.ID {
|
||||
return admin.CanDeleteMessages
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
+12
-92
@@ -2,122 +2,42 @@ package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot *TipBot) anyTextHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
func (bot TipBot) anyTextHandler(ctx context.Context, m *tb.Message) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
return
|
||||
}
|
||||
|
||||
// check if user is in Database, if not, initialize wallet
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil || !user.Initialized {
|
||||
return bot.startHandler(ctx, m)
|
||||
}
|
||||
|
||||
// check if the user clicked on the balance button
|
||||
if strings.HasPrefix(m.Text, MainMenuCommandBalance) {
|
||||
bot.tryDeleteMessage(m)
|
||||
// overwrite the message text so it doesn't cause an infinite loop
|
||||
// because balanceHandler calls anyTextHAndler...
|
||||
m.Text = ""
|
||||
return bot.balanceHandler(ctx, m)
|
||||
bot.startHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
// could be an invoice
|
||||
anyText := strings.ToLower(m.Text)
|
||||
if lightning.IsInvoice(anyText) {
|
||||
m.Text = "/pay " + anyText
|
||||
return bot.payHandler(ctx, m)
|
||||
bot.payHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
if lightning.IsLnurl(anyText) {
|
||||
m.Text = "/lnurl " + anyText
|
||||
return bot.lnurlHandler(ctx, m)
|
||||
}
|
||||
if c := stateCallbackMessage[user.StateKey]; c != nil {
|
||||
return c(ctx, m)
|
||||
//ResetUserState(user, bot)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
type EnterUserStateData struct {
|
||||
ID string `json:"ID"` // holds the ID of the tx object in bunt db
|
||||
Type string `json:"Type"` // holds type of the tx in bunt db (needed for type checking)
|
||||
Amount int64 `json:"Amount"` // holds the amount entered by the user mSat
|
||||
AmountMin int64 `json:"AmountMin"` // holds the minimum amount that needs to be entered mSat
|
||||
AmountMax int64 `json:"AmountMax"` // holds the maximum amount that needs to be entered mSat
|
||||
OiringalCommand string `json:"OiringalCommand"` // hold the originally entered command for evtl later use
|
||||
}
|
||||
|
||||
func (bot *TipBot) askForUser(ctx context.Context, id string, eventType string, originalCommand string) (enterUserStateData *EnterUserStateData, err error) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return // errors.New("user has no wallet"), 0
|
||||
}
|
||||
enterUserStateData = &EnterUserStateData{
|
||||
ID: id,
|
||||
Type: eventType,
|
||||
OiringalCommand: originalCommand,
|
||||
}
|
||||
// set LNURLPayParams in the state of the user
|
||||
stateDataJson, err := json.Marshal(enterUserStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.lnurlHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserEnterUser, string(stateDataJson))
|
||||
// Let the user enter a user and return
|
||||
bot.trySendMessage(user.Telegram, Translate(ctx, "enterUserMessage"), tb.ForceReply)
|
||||
return
|
||||
}
|
||||
|
||||
// enterAmountHandler is invoked in anyTextHandler when the user needs to enter an amount
|
||||
// the amount is then stored as an entry in the user's stateKey in the user database
|
||||
// any other handler that relies on this, needs to load the resulting amount from the database
|
||||
func (bot *TipBot) enterUserHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
// could be a LNURL
|
||||
// var lnurlregex = regexp.MustCompile(`.*?((lnurl)([0-9]{1,}[a-z0-9]+){1})`)
|
||||
if user.StateKey == lnbits.UserStateLNURLEnterAmount || user.StateKey == lnbits.UserEnterAmount {
|
||||
bot.enterAmountHandler(ctx, m)
|
||||
}
|
||||
|
||||
if !(user.StateKey == lnbits.UserEnterUser) {
|
||||
ResetUserState(user, bot)
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
if len(m.Text) < 4 || strings.HasPrefix(m.Text, "/") || m.Text == SendMenuCommandEnter {
|
||||
ResetUserState(user, bot)
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
|
||||
var EnterUserStateData EnterUserStateData
|
||||
err := json.Unmarshal([]byte(user.StateData), &EnterUserStateData)
|
||||
if err != nil {
|
||||
log.Errorf("[EnterUserHandler] %s", err.Error())
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
userstr := m.Text
|
||||
|
||||
// find out which type the object in bunt has waiting for an amount
|
||||
// we stored this in the EnterAmountStateData before
|
||||
switch EnterUserStateData.Type {
|
||||
case "CreateSendState":
|
||||
m.Text = fmt.Sprintf("/send %s", userstr)
|
||||
return bot.sendHandler(ctx, m)
|
||||
default:
|
||||
ResetUserState(user, bot)
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
+23
-18
@@ -3,7 +3,6 @@ package telegram
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -12,7 +11,7 @@ import (
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func helpTipUsage(ctx context.Context, errormsg string) string {
|
||||
@@ -31,12 +30,14 @@ func TipCheckSyntax(ctx context.Context, m *tb.Message) (bool, string) {
|
||||
return true, ""
|
||||
}
|
||||
|
||||
func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) {
|
||||
// delete the tip message after a few seconds, this is default behaviour
|
||||
defer NewMessage(m, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, fmt.Errorf("user has no wallet")
|
||||
return
|
||||
}
|
||||
|
||||
// only if message is a reply
|
||||
@@ -44,13 +45,13 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) (context.Conte
|
||||
bot.tryDeleteMessage(m)
|
||||
bot.trySendMessage(m.Sender, helpTipUsage(ctx, Translate(ctx, "tipDidYouReplyMessage")))
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "tipInviteGroupMessage"))
|
||||
return ctx, errors.Create(errors.NoReplyMessageError)
|
||||
return
|
||||
}
|
||||
|
||||
if ok, err := TipCheckSyntax(ctx, m); !ok {
|
||||
bot.trySendMessage(m.Sender, helpTipUsage(ctx, err))
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
return
|
||||
}
|
||||
|
||||
// get tip amount
|
||||
@@ -61,21 +62,22 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) (context.Conte
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpTipUsage(ctx, Translate(ctx, "tipValidAmountMessage")))
|
||||
log.Warnln(errmsg)
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
return
|
||||
}
|
||||
|
||||
err = bot.parseCmdDonHandler(ctx, m)
|
||||
if err == nil {
|
||||
return ctx, fmt.Errorf("invalid parseCmdDonHandler")
|
||||
return
|
||||
}
|
||||
// TIP COMMAND IS VALID
|
||||
from := LoadUser(ctx)
|
||||
|
||||
to := LoadReplyToUser(ctx)
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "tipYourselfMessage"))
|
||||
return ctx, fmt.Errorf("cannot tip yourself")
|
||||
return
|
||||
}
|
||||
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
@@ -89,7 +91,7 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) (context.Conte
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[/tip] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, fmt.Errorf("could not create wallet for %s", toUserStr)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,19 +112,24 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) (context.Conte
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf("%s %s", Translate(ctx, "tipErrorMessage"), err))
|
||||
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "tipErrorMessage"))
|
||||
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err)
|
||||
log.Warnln(errMsg)
|
||||
return ctx, fmt.Errorf("could not create wallet for %s", toUserStr)
|
||||
return
|
||||
}
|
||||
|
||||
// update tooltip if necessary
|
||||
messageHasTip := tipTooltipHandler(m, bot, amount, to.Initialized)
|
||||
|
||||
log.Infof("[💸 tip] Tip from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
log.Infof("[tip] Transaction sent from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
|
||||
// notify users
|
||||
bot.trySendMessage(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "tipSentMessage"), amount, toUserStrMd))
|
||||
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "tipSentMessage"), amount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[/tip] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// forward tipped message to user once
|
||||
if !messageHasTip {
|
||||
@@ -133,7 +140,5 @@ func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) (context.Conte
|
||||
if len(tipMemo) > 0 {
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(tipMemo)))
|
||||
}
|
||||
// delete the tip message after a few seconds, this is default behaviour
|
||||
NewMessage(m, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot))
|
||||
return ctx, nil
|
||||
return
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -26,22 +26,17 @@ const (
|
||||
|
||||
type TipTooltip struct {
|
||||
Message
|
||||
ID string `json:"id"`
|
||||
TipAmount int64 `json:"tip_amount"`
|
||||
TipAmount int `json:"tip_amount"`
|
||||
Ntips int `json:"ntips"`
|
||||
LastTip time.Time `json:"last_tip"`
|
||||
Tippers []*tb.User `json:"tippers"`
|
||||
}
|
||||
|
||||
func (ttt TipTooltip) Key() string {
|
||||
return fmt.Sprintf("tip-tool-tip:%s", ttt.ID)
|
||||
}
|
||||
|
||||
const maxNamesInTipperMessage = 5
|
||||
|
||||
type TipTooltipOption func(m *TipTooltip)
|
||||
|
||||
func TipAmount(amount int64) TipTooltipOption {
|
||||
func TipAmount(amount int) TipTooltipOption {
|
||||
return func(m *TipTooltip) {
|
||||
m.TipAmount = amount
|
||||
}
|
||||
@@ -55,7 +50,6 @@ func Tips(nTips int) TipTooltipOption {
|
||||
|
||||
func NewTipTooltip(m *tb.Message, opts ...TipTooltipOption) *TipTooltip {
|
||||
tipTooltip := &TipTooltip{
|
||||
ID: fmt.Sprintf("%d-%d", m.Chat.ID, m.ReplyTo.ID),
|
||||
Message: Message{
|
||||
Message: m,
|
||||
},
|
||||
@@ -105,8 +99,8 @@ func getTippersString(tippers []*tb.User) string {
|
||||
}
|
||||
|
||||
// tipTooltipExists checks if this tip is already known
|
||||
func tipTooltipExists(m *tb.Message, bot *TipBot) (bool, *TipTooltip) {
|
||||
message := NewTipTooltip(&tb.Message{Chat: &tb.Chat{ID: m.Chat.ID}, ReplyTo: &tb.Message{ID: m.ReplyTo.ID}})
|
||||
func tipTooltipExists(replyToId int, bot *TipBot) (bool, *TipTooltip) {
|
||||
message := NewTipTooltip(&tb.Message{ReplyTo: &tb.Message{ID: replyToId}})
|
||||
err := bot.Bunt.Get(message)
|
||||
if err != nil {
|
||||
return false, message
|
||||
@@ -116,48 +110,49 @@ func tipTooltipExists(m *tb.Message, bot *TipBot) (bool, *TipTooltip) {
|
||||
}
|
||||
|
||||
// tipTooltipHandler function to update the tooltip below a tipped message. either updates or creates initial tip tool tip
|
||||
func tipTooltipHandler(m *tb.Message, bot *TipBot, amount int64, initializedWallet bool) (hasTip bool) {
|
||||
func tipTooltipHandler(m *tb.Message, bot *TipBot, amount int, initializedWallet bool) (hasTip bool) {
|
||||
// todo: this crashes if the tooltip message (maybe also the original tipped message) was deleted in the mean time!!! need to check for existence!
|
||||
hasTip, ttt := tipTooltipExists(m, bot)
|
||||
log.Debugf("[tip] %s has tip: %t", ttt.ID, hasTip)
|
||||
hasTip, ttt := tipTooltipExists(m.ReplyTo.ID, bot)
|
||||
if hasTip {
|
||||
// update the tooltip with new tippers
|
||||
err := ttt.updateTooltip(bot, m.Sender, amount, !initializedWallet)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
log.Println(err)
|
||||
// could not update the message (return false to )
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
newToolTip(m, bot, amount, initializedWallet)
|
||||
tipmsg := fmt.Sprintf(tooltipTipAmountMessage, amount)
|
||||
userStr := GetUserStrMd(m.Sender)
|
||||
tipmsg = fmt.Sprintf(tooltipSingleTipMessage, tipmsg, userStr)
|
||||
|
||||
if !initializedWallet {
|
||||
tipmsg = tipmsg + fmt.Sprintf("\n%s", fmt.Sprintf(tooltipChatWithBotMessage, GetUserStrMd(bot.Telegram.Me)))
|
||||
}
|
||||
msg, err := bot.Telegram.Reply(m.ReplyTo, tipmsg, tb.Silent)
|
||||
if err != nil {
|
||||
log.Errorf("[tipTooltipHandler Reply] %s", err.Error())
|
||||
// todo: in case of error we should do something better than just return 0
|
||||
return false
|
||||
}
|
||||
message := NewTipTooltip(msg, TipAmount(amount), Tips(1))
|
||||
message.Tippers = appendUinqueUsersToSlice(message.Tippers, m.Sender)
|
||||
runtime.IgnoreError(bot.Bunt.Set(message))
|
||||
}
|
||||
// first call will return false, every following call will return true
|
||||
return hasTip
|
||||
}
|
||||
|
||||
func newToolTip(m *tb.Message, bot *TipBot, amount int64, initializedWallet bool) {
|
||||
tipmsg := fmt.Sprintf(tooltipTipAmountMessage, amount)
|
||||
userStr := GetUserStrMd(m.Sender)
|
||||
tipmsg = fmt.Sprintf(tooltipSingleTipMessage, tipmsg, userStr)
|
||||
|
||||
if !initializedWallet {
|
||||
tipmsg = tipmsg + fmt.Sprintf("\n%s", fmt.Sprintf(tooltipChatWithBotMessage, GetUserStrMd(bot.Telegram.Me)))
|
||||
}
|
||||
msg := bot.tryReplyMessage(m.ReplyTo, tipmsg, tb.Silent)
|
||||
message := NewTipTooltip(msg, TipAmount(amount), Tips(1))
|
||||
message.Tippers = appendUinqueUsersToSlice(message.Tippers, m.Sender)
|
||||
runtime.IgnoreError(bot.Bunt.Set(message))
|
||||
log.Debugf("[newToolTip]: New reply message: %d (Bunt: %s)", msg.ID, message.Key())
|
||||
}
|
||||
|
||||
// updateToolTip updates existing tip tool tip in Telegram
|
||||
func (ttt *TipTooltip) updateTooltip(bot *TipBot, user *tb.User, amount int64, notInitializedWallet bool) error {
|
||||
func (ttt *TipTooltip) updateTooltip(bot *TipBot, user *tb.User, amount int, notInitializedWallet bool) error {
|
||||
ttt.TipAmount += amount
|
||||
ttt.Ntips += 1
|
||||
ttt.Tippers = appendUinqueUsersToSlice(ttt.Tippers, user)
|
||||
ttt.LastTip = time.Now()
|
||||
ttt.editTooltip(bot, notInitializedWallet)
|
||||
log.Debugf("[updateTooltip]: Update tip tooltip (Bunt: %s)", ttt.Key())
|
||||
err := ttt.editTooltip(bot, notInitializedWallet)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return bot.Bunt.Set(ttt)
|
||||
}
|
||||
|
||||
@@ -166,15 +161,17 @@ func tipTooltipInitializedHandler(user *tb.User, bot TipBot) {
|
||||
runtime.IgnoreError(bot.Bunt.View(func(tx *buntdb.Tx) error {
|
||||
err := tx.Ascend(MessageOrderedByReplyToFrom, func(key, value string) bool {
|
||||
replyToUserId := gjson.Get(value, MessageOrderedByReplyToFrom)
|
||||
if replyToUserId.String() == strconv.FormatInt(user.ID, 10) {
|
||||
log.Debugln("[tipTooltipInitializedHandler] loading persistent tip tool tip messages")
|
||||
if replyToUserId.String() == strconv.Itoa(user.ID) {
|
||||
log.Debugln("loading persistent tip tool tip messages")
|
||||
ttt := &TipTooltip{}
|
||||
err := json.Unmarshal([]byte(value), ttt)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
// edit to remove the "chat with bot" message
|
||||
ttt.editTooltip(&bot, false)
|
||||
err = ttt.editTooltip(&bot, false)
|
||||
if err != nil {
|
||||
log.Errorf("[tipTooltipInitializedHandler] could not edit tooltip: %s", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
@@ -183,9 +180,17 @@ func tipTooltipInitializedHandler(user *tb.User, bot TipBot) {
|
||||
}))
|
||||
}
|
||||
|
||||
func (ttt TipTooltip) Key() string {
|
||||
return fmt.Sprintf("tip-tool-tip:%s", strconv.Itoa(ttt.Message.Message.ReplyTo.ID))
|
||||
}
|
||||
|
||||
// editTooltip updates the tooltip message with the new tip amount and tippers and edits it
|
||||
func (ttt *TipTooltip) editTooltip(bot *TipBot, notInitializedWallet bool) {
|
||||
func (ttt *TipTooltip) editTooltip(bot *TipBot, notInitializedWallet bool) error {
|
||||
tipToolTip := ttt.getUpdatedTipTooltipMessage(GetUserStrMd(bot.Telegram.Me), notInitializedWallet)
|
||||
bot.tryEditMessage(ttt.Message.Message, tipToolTip)
|
||||
// ttt.Message.Message.Text = m.Text
|
||||
m, err := bot.Telegram.Edit(ttt.Message.Message, tipToolTip)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ttt.Message.Message.Text = m.Text
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -45,7 +45,7 @@ func Test_getTippersString(t *testing.T) {
|
||||
func TestMessage_getTooltipMessage(t *testing.T) {
|
||||
type fields struct {
|
||||
Message Message
|
||||
TipAmount int64
|
||||
TipAmount int
|
||||
Ntips int
|
||||
LastTip time.Time
|
||||
Tippers []*tb.User
|
||||
|
||||
@@ -7,30 +7,29 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type Transaction struct {
|
||||
ID uint `gorm:"primarykey"`
|
||||
Time time.Time `json:"time"`
|
||||
Bot *TipBot `gorm:"-"`
|
||||
From *lnbits.User `json:"from" gorm:"-"`
|
||||
To *lnbits.User `json:"to" gorm:"-"`
|
||||
FromId int64 `json:"from_id" `
|
||||
ToId int64 `json:"to_id" `
|
||||
FromUser string `json:"from_user"`
|
||||
ToUser string `json:"to_user"`
|
||||
Type string `json:"type"`
|
||||
Amount int64 `json:"amount"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
ChatName string `json:"chat_name"`
|
||||
Memo string `json:"memo"`
|
||||
Success bool `json:"success"`
|
||||
FromWallet string `json:"from_wallet"`
|
||||
ToWallet string `json:"to_wallet"`
|
||||
FromLNbitsID string `json:"from_lnbits"`
|
||||
ToLNbitsID string `json:"to_lnbits"`
|
||||
Invoice lnbits.BitInvoice `gorm:"embedded;embeddedPrefix:invoice_"`
|
||||
ID uint `gorm:"primarykey"`
|
||||
Time time.Time `json:"time"`
|
||||
Bot *TipBot `gorm:"-"`
|
||||
From *lnbits.User `json:"from" gorm:"-"`
|
||||
To *lnbits.User `json:"to" gorm:"-"`
|
||||
FromId int `json:"from_id" `
|
||||
ToId int `json:"to_id" `
|
||||
FromUser string `json:"from_user"`
|
||||
ToUser string `json:"to_user"`
|
||||
Type string `json:"type"`
|
||||
Amount int `json:"amount"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
ChatName string `json:"chat_name"`
|
||||
Memo string `json:"memo"`
|
||||
Success bool `json:"success"`
|
||||
FromWallet string `json:"from_wallet"`
|
||||
ToWallet string `json:"to_wallet"`
|
||||
FromLNbitsID string `json:"from_lnbits"`
|
||||
ToLNbitsID string `json:"to_lnbits"`
|
||||
}
|
||||
|
||||
type TransactionOption func(t *Transaction)
|
||||
@@ -48,7 +47,7 @@ func TransactionType(transactionType string) TransactionOption {
|
||||
}
|
||||
}
|
||||
|
||||
func NewTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int64, opts ...TransactionOption) *Transaction {
|
||||
func NewTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int, opts ...TransactionOption) *Transaction {
|
||||
t := &Transaction{
|
||||
Bot: bot,
|
||||
From: from,
|
||||
@@ -70,27 +69,36 @@ func NewTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int6
|
||||
}
|
||||
|
||||
func (t *Transaction) Send() (success bool, err error) {
|
||||
// maybe remove comments, GTP-3 dreamed this up but it's nice:
|
||||
// if t.From.ID == t.To.ID {
|
||||
// err = fmt.Errorf("Can not send transaction to yourself.")
|
||||
// return false, err
|
||||
// }
|
||||
|
||||
// todo: remove this commend if the backend is back up
|
||||
success, err = t.SendTransaction(t.Bot, t.From, t.To, t.Amount, t.Memo)
|
||||
// success = true
|
||||
if success {
|
||||
t.Success = success
|
||||
// TODO: call post-send methods
|
||||
}
|
||||
|
||||
// save transaction to db
|
||||
tx := t.Bot.logger.Save(t)
|
||||
if tx.Error != nil {
|
||||
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err.Error())
|
||||
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err)
|
||||
log.Errorln(errMsg)
|
||||
}
|
||||
|
||||
return success, err
|
||||
}
|
||||
|
||||
func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int64, memo string) (bool, error) {
|
||||
func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int, memo string) (bool, error) {
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
|
||||
t.FromWallet = from.Wallet.ID
|
||||
t.FromLNbitsID = from.ID
|
||||
|
||||
// check if fromUser has balance
|
||||
balance, err := bot.GetUserBalance(from)
|
||||
if err != nil {
|
||||
@@ -116,32 +124,16 @@ func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits
|
||||
Memo: memo},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[Send] Error: Could not create invoice for user %s", toUserStr)
|
||||
errmsg := fmt.Sprintf("[SendTransaction] Error: Could not create invoice for user %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return false, err
|
||||
}
|
||||
t.Invoice = invoice
|
||||
// pay invoice
|
||||
_, err = from.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[Send] Payment failed (%s to %s of %d sat): %s", fromUserStr, toUserStr, amount, err.Error())
|
||||
log.Warnf(errmsg)
|
||||
return false, err
|
||||
}
|
||||
|
||||
// check if fromUser has balance
|
||||
_, err = bot.GetUserBalance(from)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
errmsg := fmt.Sprintf("[SendTransaction] Error: Payment from %s to %s of %d sat failed", fromUserStr, toUserStr, amount)
|
||||
log.Errorln(errmsg)
|
||||
return false, err
|
||||
}
|
||||
_, err = bot.GetUserBalance(to)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return false, err
|
||||
}
|
||||
|
||||
return true, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type TransactionsList struct {
|
||||
ID string `json:"id"`
|
||||
User *lnbits.User `json:"from"`
|
||||
Payments lnbits.Payments `json:"payments"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
CurrentPage int `json:"currentpage"`
|
||||
MaxPages int `json:"maxpages"`
|
||||
TxPerPage int `json:"txperpage"`
|
||||
}
|
||||
|
||||
func (txlist *TransactionsList) printTransactions(ctx context.Context) string {
|
||||
txstr := ""
|
||||
// for _, p := range payments {
|
||||
payments := txlist.Payments
|
||||
pagenr := txlist.CurrentPage
|
||||
tx_per_page := txlist.TxPerPage
|
||||
if pagenr > (len(payments)+1)/tx_per_page {
|
||||
pagenr = 0
|
||||
}
|
||||
if len(payments) < tx_per_page {
|
||||
tx_per_page = len(payments)
|
||||
}
|
||||
start := pagenr * (tx_per_page - 1)
|
||||
end := start + tx_per_page
|
||||
if end >= len(payments) {
|
||||
end = len(payments) - 1
|
||||
}
|
||||
for i := len(payments) - 1 - start; i >= len(payments)-1-end; i-- {
|
||||
p := payments[i]
|
||||
if p.Amount < 0 {
|
||||
txstr += "🔼"
|
||||
} else {
|
||||
txstr += "🔽"
|
||||
}
|
||||
if p.Pending {
|
||||
txstr += "🔄"
|
||||
}
|
||||
timestr := time.Unix(int64(p.Time), 0).UTC().Format("2006-01-02 15:04:05")
|
||||
txstr += fmt.Sprintf(" %s:", timestr)
|
||||
txstr += fmt.Sprintf(" %+d sat", p.Amount/1000)
|
||||
if p.Fee > 0 {
|
||||
txstr += fmt.Sprintf("\t(fee: %d sat)", p.Fee/1000)
|
||||
}
|
||||
memo := p.Memo
|
||||
memo_maxlen := 50
|
||||
if len(memo) > memo_maxlen {
|
||||
memo = memo[:memo_maxlen] + "..."
|
||||
}
|
||||
if len(memo) > 0 {
|
||||
txstr += fmt.Sprintf("\t✉️ %s", memo)
|
||||
}
|
||||
txstr += "\n"
|
||||
}
|
||||
txstr += fmt.Sprintf("\nTotal: %d transactions. Page %d of %d.", len(payments), txlist.CurrentPage+1, txlist.MaxPages)
|
||||
return txstr
|
||||
}
|
||||
|
||||
var (
|
||||
transactionsMeno = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnLeftTransactionsButton = inlineTipjarMenu.Data("◀️", "left_transactions")
|
||||
btnRightTransactionsButton = inlineTipjarMenu.Data("▶️", "right_transactions")
|
||||
)
|
||||
|
||||
func (bot TipBot) makeTransactionsKeyboard(ctx context.Context, txlist TransactionsList) *tb.ReplyMarkup {
|
||||
// transactionsMeno := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
leftTransactionsButton := transactionsMeno.Data("←", "left_transactions")
|
||||
rightTransactionsButton := transactionsMeno.Data("→", "right_transactions")
|
||||
leftTransactionsButton.Data = txlist.ID
|
||||
rightTransactionsButton.Data = txlist.ID
|
||||
transactionsMeno.Inline(
|
||||
transactionsMeno.Row(
|
||||
leftTransactionsButton,
|
||||
rightTransactionsButton),
|
||||
)
|
||||
return transactionsMeno
|
||||
}
|
||||
|
||||
func (bot *TipBot) transactionsHandler(ctx context.Context, m *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
transactionsListInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
|
||||
if err != nil {
|
||||
payments, err := bot.Client.Payments(*user.Wallet)
|
||||
if err != nil {
|
||||
log.Errorf("[transactions] Error: %s", err.Error())
|
||||
return
|
||||
}
|
||||
// var payments lnbits.Payments
|
||||
// paymentsInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
|
||||
// if err != nil {
|
||||
// log.Info("Getting from lnbits")
|
||||
// paymentsInterface, err = bot.Client.Payments(*user.Wallet)
|
||||
// if err != nil {
|
||||
// log.Errorf("[transactions] Error: %s", err.Error())
|
||||
// return
|
||||
// }
|
||||
// bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), paymentsInterface, &store.Options{Expiration: 1 * time.Minute})
|
||||
// }
|
||||
// payments = paymentsInterface.(lnbits.Payments)
|
||||
tx_per_page := 20
|
||||
transactionsListInterface = TransactionsList{
|
||||
ID: fmt.Sprintf("txlist-%d-%s", user.Telegram.ID, RandStringRunes(5)),
|
||||
User: user,
|
||||
Payments: payments,
|
||||
LanguageCode: ctx.Value("userLanguageCode").(string),
|
||||
CurrentPage: 0,
|
||||
TxPerPage: tx_per_page,
|
||||
MaxPages: (len(payments)+1)/tx_per_page + 1,
|
||||
}
|
||||
}
|
||||
transactionsList := transactionsListInterface.(TransactionsList)
|
||||
bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), transactionsList, &store.Options{Expiration: 1 * time.Minute})
|
||||
txstr := transactionsList.printTransactions(ctx)
|
||||
bot.trySendMessage(m.Sender, txstr, bot.makeTransactionsKeyboard(ctx, transactionsList))
|
||||
}
|
||||
|
||||
func (bot *TipBot) transactionsScrollLeftHandler(ctx context.Context, c *tb.Callback) {
|
||||
user := LoadUser(ctx)
|
||||
transactionsListInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
|
||||
if err != nil {
|
||||
log.Info("Transactions not in cache anymore")
|
||||
return
|
||||
}
|
||||
transactionsList := transactionsListInterface.(TransactionsList)
|
||||
|
||||
if c.Sender.ID == transactionsList.User.Telegram.ID {
|
||||
if transactionsList.CurrentPage < transactionsList.MaxPages-1 {
|
||||
transactionsList.CurrentPage++
|
||||
} else {
|
||||
return
|
||||
}
|
||||
bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), transactionsList, &store.Options{Expiration: 1 * time.Minute})
|
||||
bot.tryEditMessage(c.Message, transactionsList.printTransactions(ctx), bot.makeTransactionsKeyboard(ctx, transactionsList))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (bot *TipBot) transactionsScrollRightHandler(ctx context.Context, c *tb.Callback) {
|
||||
user := LoadUser(ctx)
|
||||
transactionsListInterface, err := bot.Cache.Get(fmt.Sprintf("%s_transactions", user.Name))
|
||||
if err != nil {
|
||||
log.Info("Transactions not in cache anymore")
|
||||
return
|
||||
}
|
||||
transactionsList := transactionsListInterface.(TransactionsList)
|
||||
|
||||
if c.Sender.ID == transactionsList.User.Telegram.ID {
|
||||
if transactionsList.CurrentPage > 0 {
|
||||
transactionsList.CurrentPage--
|
||||
} else {
|
||||
return
|
||||
}
|
||||
bot.Cache.Set(fmt.Sprintf("%s_transactions", user.Name), transactionsList, &store.Options{Expiration: 1 * time.Minute})
|
||||
bot.tryEditMessage(c.Message, transactionsList.printTransactions(ctx), bot.makeTransactionsKeyboard(ctx, transactionsList))
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -3,15 +3,13 @@ package telegram
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func SetUserState(user *lnbits.User, bot *TipBot, stateKey lnbits.UserStateKey, stateData string) {
|
||||
@@ -61,16 +59,16 @@ func appendUinqueUsersToSlice(slice []*tb.User, i *tb.User) []*tb.User {
|
||||
return append(slice, i)
|
||||
}
|
||||
|
||||
func (bot *TipBot) GetUserBalanceCached(user *lnbits.User) (amount int64, err error) {
|
||||
func (bot *TipBot) GetUserBalanceCached(user *lnbits.User) (amount int, err error) {
|
||||
u, err := bot.Cache.Get(fmt.Sprintf("%s_balance", user.Name))
|
||||
if err != nil {
|
||||
return bot.GetUserBalance(user)
|
||||
}
|
||||
cachedBalance := u.(int64)
|
||||
cachedBalance := u.(int)
|
||||
return cachedBalance, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
|
||||
func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int, err error) {
|
||||
wallet, err := bot.Client.Info(*user.Wallet)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[GetUserBalance] Error: Couldn't fetch user %s's info from LNbits: %s", GetUserStr(user.Telegram), err.Error())
|
||||
@@ -83,23 +81,19 @@ func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
|
||||
return
|
||||
}
|
||||
// msat to sat
|
||||
amount = int64(wallet.Balance) / 1000
|
||||
log.Debugf("[GetUserBalance] %s's balance: %d sat\n", GetUserStr(user.Telegram), amount)
|
||||
amount = int(wallet.Balance) / 1000
|
||||
log.Infof("[GetUserBalance] %s's balance: %d sat\n", GetUserStr(user.Telegram), amount)
|
||||
|
||||
// update user balance in cache
|
||||
bot.Cache.Set(
|
||||
fmt.Sprintf("%s_balance", user.Name),
|
||||
amount,
|
||||
&store.Options{Expiration: 1 * time.Hour},
|
||||
&store.Options{Expiration: 30 * time.Second},
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -109,7 +103,6 @@ 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
|
||||
@@ -125,16 +118,3 @@ 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
|
||||
}
|
||||
|
||||
@@ -1,18 +1,10 @@
|
||||
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"
|
||||
|
||||
_ "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"
|
||||
@@ -20,7 +12,7 @@ import (
|
||||
|
||||
// setLogger will initialize the log format
|
||||
func setLogger() {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
log.SetLevel(log.InfoLevel)
|
||||
customFormatter := new(log.TextFormatter)
|
||||
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
|
||||
customFormatter.FullTimestamp = true
|
||||
@@ -30,39 +22,13 @@ func setLogger() {
|
||||
func main() {
|
||||
// set logger
|
||||
setLogger()
|
||||
|
||||
defer withRecovery()
|
||||
price.NewPriceWatcher().Start()
|
||||
bot := telegram.NewBot()
|
||||
startApiServer(&bot)
|
||||
webhook.NewServer(&bot)
|
||||
lnurl.NewServer(&bot)
|
||||
price.NewPriceWatcher().Start()
|
||||
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 {
|
||||
|
||||
@@ -21,7 +21,7 @@ func IsInvoice(message string) bool {
|
||||
|
||||
func IsLnurl(message string) bool {
|
||||
message = strings.ToLower(message)
|
||||
if strings.HasPrefix(message, "lnurl") || strings.HasPrefix(message, "lightning:lnurl") {
|
||||
if strings.HasPrefix(message, "lnurl") {
|
||||
// string must be a single word
|
||||
if !strings.Contains(message, " ") {
|
||||
return true
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 39 KiB After Width: | Height: | Size: 22 KiB |
+3
-22
@@ -40,7 +40,6 @@ sendButtonMessage = """✅ Senden"""
|
||||
payButtonMessage = """✅ Bezahlen"""
|
||||
payReceiveButtonMessage = """💸 Bezahlen"""
|
||||
receiveButtonMessage = """✅ Empfangen"""
|
||||
withdrawButtonMessage = """✅ Abheben"""
|
||||
cancelButtonMessage = """🚫 Abbrechen"""
|
||||
collectButtonMessage = """✅ Einsammeln"""
|
||||
nextButtonMessage = """Vor"""
|
||||
@@ -118,16 +117,12 @@ advancedMessage = """%s
|
||||
📖 Du kannst Inline Befehle in jedem Chat verwenden, sogar in privaten Nachrichten. Warte eine Sekunde, nachdem du den Befehl eingegeben hast und *klicke* auf das Ergebnis, statt Enter einzugeben.
|
||||
|
||||
⚙️ *Fortgeschrittene Befehle*
|
||||
*/transactions* 📃 Liste deiner Transaktionen.
|
||||
*/link* 🔗 Verbinde dein Wallet mit [BlueWallet](https://bluewallet.io/) oder [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl empfangen oder senden: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Erzeuge einen Zapfhahn: `/faucet <gesamt> <pro_user>`
|
||||
*/tipjar* 🍯 Erzeuge eine Spendendose: `/tipjar <gesamt> <pro_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """⌨️ Gebe einen Betrag zwischen %d und %d sat ein."""
|
||||
enterAmountMessage = """⌨️ Gebe einen Betrag ein."""
|
||||
errorReasonMessage = """🚫 Fehler: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Richte dein Wallet ein..."""
|
||||
@@ -232,26 +227,12 @@ lnurlPaymentFailed = """🚫 Zahlung fehlgeschlagen: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Ungültiger Betrag."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Betrag muss zwischen %d und %d sat liegen."""
|
||||
lnurlNoUsernameMessage = """🚫 Du musst einen Telegram Username anlegen, um per LNURL Zahlungen zu empfangen."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Gebe einen Betrag zwischen %d und %d sat ein."""
|
||||
lnurlHelpText = """📖 Ups, das hat nicht geklappt. %s
|
||||
|
||||
*Befehl:* `/lnurl [betrag] <lnurl>`
|
||||
*Beispiel:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL 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"""
|
||||
lnurlPreparingWithdraw = """🧮 Bereite Abhebung vor..."""
|
||||
lnurlWithdrawFailed = """🚫 Abhebung gescheitert."""
|
||||
lnurlWithdrawCancelled = """🚫 Abhebung abgebrochen."""
|
||||
lnurlWithdrawSuccess = """✅ Abhebung angefordert."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Verbinde dein Wallet*
|
||||
@@ -269,7 +250,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 %s's Zapfhahn zu zapfen.
|
||||
inlineFaucetMessage = """Drücke ✅ um %d sat aus diesem Zapfhahn zu zapfen.
|
||||
|
||||
🚰 Verbleibend: %d/%d sat (%d/%d gezapft)
|
||||
%s"""
|
||||
|
||||
+10
-31
@@ -40,7 +40,6 @@ sendButtonMessage = """✅ Send"""
|
||||
payButtonMessage = """✅ Pay"""
|
||||
payReceiveButtonMessage = """💸 Pay"""
|
||||
receiveButtonMessage = """✅ Receive"""
|
||||
withdrawButtonMessage = """✅ Withdraw"""
|
||||
cancelButtonMessage = """🚫 Cancel"""
|
||||
collectButtonMessage = """✅ Collect"""
|
||||
nextButtonMessage = """Next"""
|
||||
@@ -82,7 +81,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._
|
||||
@@ -121,17 +120,12 @@ advancedMessage = """%s
|
||||
📖 You can use inline commands in every chat, even in private conversations. Wait a second after entering an inline command and *click* the result, don't press enter.
|
||||
|
||||
⚙️ *Advanced commands*
|
||||
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/).
|
||||
*/lnurl* ⚡️ Lnurl receive or pay: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Create a faucet: `/faucet <capacity> <per_user>`
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Enter an amount between %d and %d sat."""
|
||||
enterAmountMessage = """💯 Enter an amount."""
|
||||
enterUserMessage = """👤 Enter a user."""
|
||||
errorReasonMessage = """🚫 Error: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Setting up your wallet..."""
|
||||
@@ -195,10 +189,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 to a Lightning address."""
|
||||
invalidInvoiceHelpMessage = """Did you enter a valid Lightning invoice? Try /send if you want to send to a Telegram user or 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. Reserve at least 1% for fees."""
|
||||
feeReserveMessage = """⚠️ Sending your entire balance might fail because of network fees. If it fails, try sending a bit less."""
|
||||
invoicePaymentFailedMessage = """🚫 Payment failed: %s"""
|
||||
invoiceUndefinedErrorMessage = """Could not pay invoice."""
|
||||
confirmPayInvoiceMessage = """Do you want to send this payment?\n\n💸 Amount: %d sat"""
|
||||
@@ -236,26 +230,13 @@ lnurlPaymentFailed = """🚫 Payment failed: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Invalid amount."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Amount must be between %d and %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 You need to set a Telegram username to receive payments via LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Enter an amount between %d and %d sat."""
|
||||
lnurlEnterAmountMessage = """⌨️ Enter an amount."""
|
||||
lnurlHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
*Usage:* `/lnurl [amount] <lnurl>`
|
||||
*Example:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL 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"""
|
||||
lnurlPreparingWithdraw = """🧮 Preparing withdrawal..."""
|
||||
lnurlWithdrawFailed = """🚫 Withdrawal failed."""
|
||||
lnurlWithdrawCancelled = """🚫 Withdrawal cancelled."""
|
||||
lnurlWithdrawSuccess = """✅ Withdrawal requested."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Link your wallet*
|
||||
@@ -264,8 +245,7 @@ walletConnectMessage = """🔗 *Link your wallet*
|
||||
|
||||
- *BlueWallet:* Press *New wallet*, *Import wallet*, *Scan or import a file*, and scan the QR code.
|
||||
- *Zeus:* Copy the URL below, press *Add a new node*, *Import* (the URL), *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Couldn't link your wallet. Please try again later."""
|
||||
linkHiddenMessage = """🔍 Link hidden. Enter /link to see it again."""
|
||||
couldNotLinkMessage = """🚫 Couldn't link your wallet. Please try again later."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
@@ -274,7 +254,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 %s's faucet.
|
||||
inlineFaucetMessage = """Press ✅ to collect %d sat from this faucet.
|
||||
|
||||
🚰 Remaining: %d/%d sat (given to %d/%d users)
|
||||
%s"""
|
||||
@@ -282,12 +262,11 @@ 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 or too low (min 5 sat)."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 Peruser amount not divisor of capacity."""
|
||||
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>`
|
||||
|
||||
+5
-48
@@ -17,7 +17,7 @@ linkCommandStr = """enlace"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """grifo"""
|
||||
|
||||
tipjarCommandStr = """alcancía"""
|
||||
tipjarCommandStr = """bote"""
|
||||
receiveCommandStr = """recibir"""
|
||||
hideCommandStr = """ocultar"""
|
||||
volcanoCommandStr = """volcán"""
|
||||
@@ -117,20 +117,15 @@ advancedMessage = """%s
|
||||
📖 Puedes usar comandos _inline_ en todos los chats, incluso en las conversaciones privadas. Espera un segundo después de introducir un comando _inline_ y *haz clic* en el resultado, no pulses enter.
|
||||
|
||||
⚙️ *Comandos avanzados*
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/link* 🔗 Enlaza tu monedero a [ BlueWallet ](https://bluewallet.io/) o [ Zeus ](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl recibir o pagar: `/lnurl` o `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Crear un grifo: `/faucet <capacidad> <por_usuario>`
|
||||
*/tipjar* 🍯 Crear un tipjar: `/tipjar <capacidad> <por_usuario>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Introduce un monto entre %d y %d sat."""
|
||||
enterAmountMessage = """💯 Introduce un monto."""
|
||||
enterUserMessage = """👤 Introduce un usuario."""
|
||||
errorReasonMessage = """🚫 Error: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Configurando tu monedero..."""
|
||||
startSettingWalletMessage = """🧮 Configurar tu monedero..."""
|
||||
startWalletCreatedMessage = """🧮 Monedero creado."""
|
||||
startWalletReadyMessage = """✅ *Tu monedero está listo.*"""
|
||||
startWalletErrorMessage = """🚫 Error al iniciar tu monedero. Vuelve a intentarlo más tarde."""
|
||||
@@ -232,26 +227,12 @@ lnurlPaymentFailed = """🚫 Pago fallido: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Monto inválido."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 El monto debe estar entre %d y %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Tienes que establecer un nombre de usuario de Telegram para recibir pagos a través de LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Introduce un monto entre %d y %d sat."""
|
||||
lnurlHelpText = """📖 Oops, eso no funcionó. %s
|
||||
|
||||
*Uso:* `/lnurl [monto] <lnurl>`
|
||||
*Ejemplo:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL 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"""
|
||||
lnurlPreparingWithdraw = """🧮 Preparando retiro..."""
|
||||
lnurlWithdrawFailed = """🚫 Retiro fallido."""
|
||||
lnurlWithdrawCancelled = """🚫 Retiro cancelado."""
|
||||
lnurlWithdrawSuccess = """✅ Retiro solicitado."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Enlaza tu monedero*
|
||||
@@ -269,7 +250,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 de %s.
|
||||
inlineFaucetMessage = """Pulsa ✅ para cobrar %d sat de este grifo.
|
||||
|
||||
🚰 Restante: %d/%d sat (dado a %d/%d usuarios)
|
||||
%s"""
|
||||
@@ -317,27 +298,3 @@ inlineReceiveCreateWalletMessage = """Chatea con %s 👈 para gestionar tu carte
|
||||
inlineReceiveYourselfMessage = """📖 No puedes pagarte a ti mismo."""
|
||||
inlineReceiveFailedMessage = """🚫 Recepción fallida."""
|
||||
inlineReceiveCancelledMessage = """🚫 Recepción cancelada."""
|
||||
|
||||
# TIPJAR
|
||||
|
||||
inlineQueryTipjarTitle = """🍯 Crear una alcancía."""
|
||||
inlineQueryTipjarDescription = """Uso: @%s alcancía <capacidad> <por_usuario>"""
|
||||
inlineResultTipjarTitle = """🍯 Crear una alcancía de %d sat."""
|
||||
inlineResultTipjarDescription = """👉 Haz clic aquí para crear una alcancía en este chat."""
|
||||
|
||||
inlineTipjarMessage = """Pulsa 💸 para *pagar %d sat* a esa alcancía de %s.
|
||||
|
||||
🙏 Dados: *%d*/%d sat (por %d usuarios)
|
||||
%s"""
|
||||
inlineTipjarEndedMessage = """🍯 La alcancía de %s está llena ⭐️\n\n🏅 %d sat dados por %d usuários."""
|
||||
inlineTipjarAppendMemo = """\n✉️ %s"""
|
||||
inlineTipjarCancelledMessage = """🚫 Alcancía cancelada."""
|
||||
inlineTipjarInvalidPeruserAmountMessage = """🚫 El monto por usuario no es divisor de la capacidad."""
|
||||
inlineTipjarInvalidAmountMessage = """🚫 Monto inválido."""
|
||||
inlineTipjarSentMessage = """🍯 %d sat enviado(s) a %s."""
|
||||
inlineTipjarReceivedMessage = """🍯 %s te envió %d sat."""
|
||||
inlineTipjarHelpTipjarInGroup = """Crea una alcancía en un grupo con el bot dentro o utiliza el 👉 comando _inline_ (/advanced para más)."""
|
||||
inlineTipjarHelpText = """📖 Oops, eso no funcionó. %s
|
||||
|
||||
*Uso:* `/tipjar <capacidad> <por_usuario>`
|
||||
*Ejemplo:* `/tipjar 210 21`"""
|
||||
|
||||
@@ -117,17 +117,12 @@ advancedMessage = """%s
|
||||
📖 Vous pouvez utiliser ces commandes dans tous les chats et même dans les conversations privées. Attendez une seconde après avoir tapé une commandé puis *click* sur le résultat, n'appuyez pas sur entrée.
|
||||
|
||||
⚙️ *Commandes avancées*
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/link* 🔗 Lier votre wallet à [BlueWallet](https://bluewallet.io/) ou [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl recevoir ou payer: `/lnurl` ou `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Créer un faucet: `/faucet <capacité> <par_utilisateur>`
|
||||
*/tipjar* 🍯 Créer un tipjar: `/tipjar <capacité> <par_utilisateur>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Choisissez un montant entre %d et %d sat."""
|
||||
enterAmountMessage = """💯 Choisissez un montant."""
|
||||
enterUserMessage = """👤 Choisissez un utilisateur."""
|
||||
errorReasonMessage = """🚫 Erreur: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Création de votre wallet..."""
|
||||
@@ -232,6 +227,7 @@ lnurlPaymentFailed = """🚫 Echec du paiement : %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Montant incorrect."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Le montant doit être entre %d et %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Vous devez avoir un nom d'utilisateur Telegram pour recevoir un paiement via LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Choisissez un montant entre %d et %d sat."""
|
||||
lnurlHelpText = """📖 Oops, cela n'a pas fonctionné. %s
|
||||
|
||||
*Usage:* `/lnurl [montant] <lnurl>`
|
||||
@@ -254,7 +250,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 de %s.
|
||||
inlineFaucetMessage = """Appuyez sur ✅ pour collecter %d sat de ce faucet.
|
||||
|
||||
🚰 Restant: %d/%d sat (envoyé à %d/%d utilisateurs)
|
||||
%s"""
|
||||
|
||||
+3
-15
@@ -117,17 +117,12 @@ advancedMessage = """%s
|
||||
📖 Kamu dapat menggunakan sebaris perintah di tiap percakapan, bahkan di percakapan privat. Tunggu sejenak setelah memasukkan sebaris perintah lalu *pencet* hasilnya, jangan tekan enter.
|
||||
|
||||
⚙️ *Perintah lanjutan*
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/link* 🔗 Menghubungkan dompet mu ke [BlueWallet](https://bluewallet.io/) atau [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl menerima atau membayar: `/lnurl` atau `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Membuat sebuah keran `/faucet <kapasitas> <per_pengguna>`
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Masukkan jumlah diantara %d dan %d sat."""
|
||||
enterAmountMessage = """💯 Masukkan jumlah."""
|
||||
enterUserMessage = """👤 Masukkan user."""
|
||||
errorReasonMessage = """🚫 Error: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Sedang menyiapkan dompet mu..."""
|
||||
@@ -232,19 +227,12 @@ lnurlPaymentFailed = """🚫 Pembayaran gagal: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Jumlah tidak benar."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Jumlah harus diantara %d dan %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Kamu harus mengatur nama pengguna Telegram untuk menerima pembayaran melalui LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Masukkan jumlah diantara %d dan %d sat."""
|
||||
lnurlHelpText = """📖 Waduh, itu tidak berhasil. %s
|
||||
|
||||
*Usage:* `/lnurl [jumlah] <lnurl>`
|
||||
*Example:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL PENARIKAN
|
||||
|
||||
confirmLnurlWithdrawMessage = """Apakah anda ingin melakukan penarikan ini?\n\n💸 Jumlah: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Mempersiapkan penarikan..."""
|
||||
lnurlWithdrawFailed = """🚫 Penarikan gagal."""
|
||||
lnurlWithdrawCancelled = """🚫 Penarikan dibatalkan."""
|
||||
lnurlWithdrawSuccess = """✅ Penarikan diajukan."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Hubungkan dompet mu*
|
||||
@@ -262,7 +250,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 %s.
|
||||
inlineFaucetMessage = """Tekan ✅ untuk mengambil %d sat dari keran ini.
|
||||
|
||||
🚰 Tersisa: %d/%d sat (diberikan kepada %d/%d pengguna)
|
||||
%s"""
|
||||
|
||||
@@ -117,17 +117,12 @@ advancedMessage = """%s
|
||||
📖 Puoi usare i comandi in linea in ogni chat, anche nelle conversazioni private. Attendi un secondo dopo aver inviato un comando in linea e *clicca* sull'azione desiderata, non premere invio.
|
||||
|
||||
⚙️ *Comandi avanzati*
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/link* 🔗 Crea un collegamento al tuo wallet [BlueWallet](https://bluewallet.io/) o [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Ricevi o paga un Lnurl: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Crea una distribuzione: `/faucet <totale> <per_utente>`
|
||||
*/tipjar* 🍯 Crea un tipjar: `/tipjar <totale> <per_utente>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Imposta un ammontare tra %d e %d sat."""
|
||||
enterAmountMessage = """💯 Imposta un ammontare."""
|
||||
enterUserMessage = """👤 Imposta un utente."""
|
||||
errorReasonMessage = """🚫 Errore: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Sto creando il tuo wallet..."""
|
||||
@@ -232,6 +227,7 @@ lnurlPaymentFailed = """🚫 Pagamento non riuscito: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Ammontare non valido."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 L'ammontare deve essere compreso tra %d e %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Devi impostare un nome utente Telegram per ricevere pagamenti tramite un LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Imposta un ammontare tra %d e %d sat."""
|
||||
lnurlHelpText = """📖 Ops, non ha funzionato. %s
|
||||
|
||||
*Sintassi:* `/lnurl [ammontare] <lnurl>`
|
||||
@@ -254,7 +250,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 da %s.
|
||||
inlineFaucetMessage = """Premi ✅ per riscuotere %d sat da questa distribuzione.
|
||||
|
||||
🚰 Rimanente: %d/%d sat (distribuiti a %d/%d utenti)
|
||||
%s"""
|
||||
|
||||
+3
-15
@@ -117,17 +117,12 @@ advancedMessage = """%s
|
||||
📖 Je kunt inline commando's in elke chat gebruiken, zelfs in privé gesprekken. Wacht een seconde na het invoeren van een inline commando en *klik* op het resultaat, druk niet op enter.
|
||||
|
||||
⚙️ *Geavanceerde opdrachten*
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/link* 🔗 Koppel uw wallet aan [BlueWallet](https://bluewallet.io/) of [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl ontvangen of betalen: `/lnurl` of `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Maak een kraan: `/faucet <capacity> <per_user>`
|
||||
*/tipjar* 🍯 Maak een tipjar: `/tipjar <capacity> <per_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Voer een bedrag in tussen %d en %d sat."""
|
||||
enterAmountMessage = """💯 Voer een bedrag."""
|
||||
enterUserMessage = """👤 Voer een gebruiker."""
|
||||
errorReasonMessage = """🚫 Fout: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Uw wallet instellen..."""
|
||||
@@ -232,19 +227,12 @@ lnurlPaymentFailed = """🚫 Betaling mislukt: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Ongeldig bedrag."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Bedrag moet liggen tussen %d en %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 U moet een Telegram gebruikersnaam instellen om betalingen te ontvangen via LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Voer een bedrag in tussen %d en %d sat."""
|
||||
lnurlHelpText = """📖 Oeps, dat werkte niet. %s
|
||||
|
||||
*Usage:* `/lnurl [bedrag] <lnurl>`
|
||||
*Example:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """Wilt u deze opname maken?💸 Bedrag: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Opname aan het voorbereiden..."""
|
||||
lnurlWithdrawFailed = """🚫 Opname mislukt."""
|
||||
lnurlWithdrawCancelled = """🚫 Opname geannuleerd."""
|
||||
lnurlWithdrawSuccess = """✅ Opname aangevraagd."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Koppel uw wallet*
|
||||
@@ -262,7 +250,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 van %s.
|
||||
inlineFaucetMessage = """Druk op ✅ om %d sat te verzamelen van deze kraan.
|
||||
|
||||
🚰 Remaining: %d/%d sat (given to %d/%d users)
|
||||
%s"""
|
||||
|
||||
+4
-47
@@ -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._
|
||||
@@ -117,17 +117,12 @@ advancedMessage = """%s
|
||||
📖 Você pode usar comandos _inline_ em todas as conversas, mesmo em conversas privadas. Espere um segundo após inserir um comando _inline_ e *clique* no resultado, não pressione enter.
|
||||
|
||||
⚙️ *Comandos avançados*
|
||||
*/transactions* 📃 List your transactions.
|
||||
*/link* 🔗 Vincule sua carteira a [ BlueWallet ](https://bluewallet.io/) ou [ Zeus ](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Receber ou pagar com lnurl: `/lnurl` o `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Criar uma torneira: `/faucet <capacidade> <por_usuário>`
|
||||
*/tipjar* 🍯 Criar uma tipjar: `/tipjar <capacidade> <por_usuário>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Insira uma quantia entre %d e %d sat."""
|
||||
enterAmountMessage = """💯 Insira uma quantia."""
|
||||
enterUserMessage = """👤 Insira um usuário."""
|
||||
errorReasonMessage = """🚫 Erro: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Preparando sua carteira..."""
|
||||
@@ -232,26 +227,12 @@ lnurlPaymentFailed = """🚫 Falha no pagamento: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Quantia inválida."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 A quantia deve estar entre %d e %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Você precisa configurar um nome de usuário de Telegram para receber pagamentos através do LNURL."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ Insira uma quantia entre %d e %d sat."""
|
||||
lnurlHelpText = """📖 Opa, isso não funcionou. %s
|
||||
|
||||
*Uso:* `/lnurl [quantidade] <lnurl>`
|
||||
*Exemplo:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL 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"""
|
||||
lnurlPreparingWithdraw = """🧮 Preparando o saque..."""
|
||||
lnurlWithdrawFailed = """🚫 Saque falhou."""
|
||||
lnurlWithdrawCancelled = """🚫 Saque cancelado."""
|
||||
lnurlWithdrawSuccess = """✅ Saque solicitado."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Vincule sua carteira*
|
||||
@@ -269,7 +250,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 de %s.
|
||||
inlineFaucetMessage = """Aperte ✅ para coletar %d sat desta torneira.
|
||||
|
||||
🚰 Restante: %d/%d sat (para %d/%d usuários)
|
||||
%s"""
|
||||
@@ -317,27 +298,3 @@ inlineReceiveCreateWalletMessage = """Bate-papo com %s 👈 para administrar sua
|
||||
inlineReceiveYourselfMessage = """📖 Você não pode pagar a si mesmo."""
|
||||
inlineReceiveFailedMessage = """🚫 O recebimento falhou."""
|
||||
inlineReceiveCancelledMessage = """🚫 Recepção cancelada."""
|
||||
|
||||
# TIPJAR
|
||||
|
||||
inlineQueryTipjarTitle = """🍯 Criar um cofrinho."""
|
||||
inlineQueryTipjarDescription = """Uso: @%s cofrinho <capacidade> <por_usuário>"""
|
||||
inlineResultTipjarTitle = """🍯 Criar um cofrinho de %d sat."""
|
||||
inlineResultTipjarDescription = """👉 Clique aqui para criar um cofrinho neste chat."""
|
||||
|
||||
inlineTipjarMessage = """Pressione 💸 para *pagar %d sat* a esse cofrinho de %s.
|
||||
|
||||
🙏 Doados: *%d*/%d sat (por %d usuários)
|
||||
%s"""
|
||||
inlineTipjarEndedMessage = """🍯 O cofrinho de %s está cheio ⭐️\n\n🏅 %d sat doados por %d usuários."""
|
||||
inlineTipjarAppendMemo = """\n✉️ %s"""
|
||||
inlineTipjarCancelledMessage = """🚫 Cofrinho cancelado."""
|
||||
inlineTipjarInvalidPeruserAmountMessage = """🚫 Quantidade por usuário não divisor da capacidade."""
|
||||
inlineTipjarInvalidAmountMessage = """🚫 Quantia inválida."""
|
||||
inlineTipjarSentMessage = """🍯 %d sat enviado(s) a %s."""
|
||||
inlineTipjarReceivedMessage = """🍯 %s lhe enviou %d sat."""
|
||||
inlineTipjarHelpTipjarInGroup = """Criar uma cofrinho em grupo com o bot dentro ou usar o 👉 comando_inline_ (/advanced para mais)."""
|
||||
inlineTipjarHelpText = """📖 Opa, isso não funcionou. %s
|
||||
|
||||
*Uso:* `/tipjar <capacidade> <por_usuário>`
|
||||
*Exemplo:* `/tipjar 210 21`"""
|
||||
|
||||
@@ -1,340 +0,0 @@
|
||||
# COMMANDS
|
||||
|
||||
helpCommandStr = """справка"""
|
||||
basicsCommandStr = """основы"""
|
||||
tipCommandStr = """tip"""
|
||||
balanceCommandStr = """баланс"""
|
||||
sendCommandStr = """отправить"""
|
||||
invoiceCommandStr = """инвойс"""
|
||||
payCommandStr = """оплатить"""
|
||||
donateCommandStr = """пожертвовать"""
|
||||
advancedCommandStr = """детально"""
|
||||
transactionsCommandStr = """транзакции"""
|
||||
logCommandStr = """лог"""
|
||||
listCommandStr = """список"""
|
||||
|
||||
linkCommandStr = """link"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """faucet"""
|
||||
|
||||
tipjarCommandStr = """tipjar"""
|
||||
receiveCommandStr = """получить"""
|
||||
hideCommandStr = """спрятать"""
|
||||
volcanoCommandStr = """volcano"""
|
||||
showCommandStr = """показать"""
|
||||
optionsCommandStr = """опции"""
|
||||
settingsCommandStr = """настройки"""
|
||||
saveCommandStr = """сохранить"""
|
||||
deleteCommandStr = """удалить"""
|
||||
infoCommandStr = """инфо"""
|
||||
|
||||
# NOTIFICATIONS
|
||||
|
||||
cantDoThatMessage = """Вы не можете это сделать."""
|
||||
cantClickMessage = """Вы не можете нажать на эту кнопку."""
|
||||
balanceTooLowMessage = """Недостаточно средств."""
|
||||
|
||||
# BUTTONS
|
||||
|
||||
sendButtonMessage = """✅ Отправить"""
|
||||
payButtonMessage = """✅ Оплатить"""
|
||||
payReceiveButtonMessage = """💸 Оплатить"""
|
||||
receiveButtonMessage = """✅ Получить"""
|
||||
withdrawButtonMessage = """✅ Вывести"""
|
||||
cancelButtonMessage = """🚫 Отмена"""
|
||||
collectButtonMessage = """✅ Забрать"""
|
||||
nextButtonMessage = """Вперед"""
|
||||
backButtonMessage = """Назад"""
|
||||
acceptButtonMessage = """Принять"""
|
||||
denyButtonMessage = """Запретить"""
|
||||
tipButtonMessage = """Tip"""
|
||||
revealButtonMessage = """Развернуть"""
|
||||
showButtonMessage = """Показать"""
|
||||
hideButtonMessage = """Спрятать"""
|
||||
joinButtonMessage = """Присоединиться"""
|
||||
optionsButtonMessage = """Опции"""
|
||||
settingsButtonMessage = """Настройки"""
|
||||
saveButtonMessage = """Сохранить"""
|
||||
deleteButtonMessage = """Удалить"""
|
||||
infoButtonMessage = """Инфо"""
|
||||
|
||||
cancelButtonEmoji = """🚫"""
|
||||
payButtonEmoji = """💸"""
|
||||
|
||||
# HELP
|
||||
|
||||
helpMessage = """⚡️ *Wallet*
|
||||
_Этот бот представляет собой кошелек Bitcoin Lightning, который может отправлять Tip (небольшие сумму в Сатоши) через Telegram. Чтобы отправить Tip, добавьте бота в групповой чат. Основной единицей чаевых являются сатоши (sat). 100 000 000 сат = 1 биткоин. Введите 📚 /basics для получения дополнительной информации._
|
||||
|
||||
❤️ *Donate*
|
||||
_Этот бот не взимает комиссии, но его работа обходится в сатоши. Если вам нравится бот, пожалуйста, поддержите этот проект пожертвованием. Чтобы сделать пожертвование, воспользуйтесь командой_ `/donate 1000`
|
||||
|
||||
%s
|
||||
|
||||
⚙️ *Команды*
|
||||
*/tip* 🏅 Ответьте на сообщение чтобы отправить Tip (небольшую сумму в Сатоши): `/tip <amount> [<memo>]`
|
||||
*/balance* 👑 Проверить баланс: `/balance`
|
||||
*/send* 💸 Отправить ссредства пользователю: `/send <количество> @<user> или <user>@ln.tips [<memo>]`
|
||||
*/invoice* ⚡️ Получить через Lightning: `/invoice <количество> [<memo>]`
|
||||
*/pay* ⚡️ Оплатить через Lightning: `/pay <инвойс>`
|
||||
*/donate* ❤️ Отправить пожертвование проекту: `/donate 1000`
|
||||
*/advanced* 🤖 Продвинутые возможности.
|
||||
*/help* 📖 Прочитайте справку."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Info*"""
|
||||
infoYourLightningAddress = """Ваш адрес в системе Lightning - `%s`"""
|
||||
|
||||
basicsMessage = """🧡 *Биткоин*
|
||||
_Биткоин - это валюта интернета. Она не имеет ограничений и децентрализована, у нее нет хозяев и контролирующих органов. Биткойн - это разумные деньги, которые быстрее, надежнее и всеохватнее, чем традиционная финансовая система._
|
||||
|
||||
🧮 *Экономика*
|
||||
_Наименьшей единицей Биткоина являются "Сатоши" (sat), а 100 000 000 sat = 1 Биткойн. В мире существует только 21 миллион биткоинов. Стоимость Биткойна выражаемая в фиатной валюте может меняться ежедневно. Однако, если вы живете по стандарту Биткойна, то 1 sat всегда будет равен 1 sat._
|
||||
|
||||
⚡️ *The Lightning Network*
|
||||
_The Lightning Network - это платежный протокол, который обеспечивает быстрые и дешевые платежи Биткоинами, практически не требующие энергии. Именно благодаря ему Биткоин доступен миллиардам людей по всему миру._
|
||||
|
||||
📲 *Lightning-кошельки*
|
||||
_Ваши средства на этом боте могут быть отправлены на любой другой Lightning-кошелек и наоборот. Рекомендуемые Lightning-кошельки для вашего телефона:_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (не требующие обслуживания), или_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(простой)_.
|
||||
|
||||
📄 *Open Source*
|
||||
_Этот бот является бесплатным и_ [с открытым исходным кодом](https://github.com/LightningTipBot/LightningTipBot) _. Вы можете запустить его на своем компьютере и использовать в своем сообществе._
|
||||
|
||||
✈️ *Telegram*
|
||||
_Добавьте этого бота в чат вашей группы Telegram для /tip сообщений. Если вы сделаете бота администратором группы, он также будет очищать команды для поддержания чистоты в чате._
|
||||
|
||||
🏛 *Условия*
|
||||
_Мы не являемся хранителями ваших средств. Мы будем действовать в ваших интересах, но мы также понимаем, что ситуация без поддержки стандарта KYC - немного сложная, до тех пор, пока мы не придумаем что-нибудь. Любая сумма, которую вы загрузите на свой кошелек, будет считаться пожертвованием. Не отдавайте нам все свои деньги. Имейте в виду, что этот бот находится в стадии бета-разработки. Используйте на свой страх и риск._
|
||||
|
||||
❤️ *Пожертвования*
|
||||
_Этот бот не взимает комиссии, но его работа обходится в сатоши. Если вам нравится бот, пожалуйста, поддержите этот проект пожертвованием. Чтобы сделать пожертвование, воспользуйтесь командой_ `/donate 1000`"""
|
||||
|
||||
helpNoUsernameMessage = """👋 Пожалуйста, установите имя пользователя в Telegram."""
|
||||
|
||||
advancedMessage = """%s
|
||||
|
||||
👉 *Команды*
|
||||
*send* 💸 Отправить Сатоши в чате: `%s send <количество> [<user>] [<memo>]`
|
||||
*receive* 🏅 Запросить оплату: `... receive <количество> [<user>] [<memo>]`
|
||||
*faucet* 🚰 Создать криптораздачу: `... faucet <ёмкость> <на_пользователя> [<memo>]`
|
||||
*tipjar* 🍯 Создать копилку: `... tipjar <ёмкость> <на_пользователя> [<memo>]`
|
||||
|
||||
📖 Вы можете использовать команды в любом чате, даже в личных беседах. Подождите секунду после ввода команды и *щелкните* результат, не нажимайте Enter..
|
||||
|
||||
⚙️ *Продвинутые команды*
|
||||
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
|
||||
*/lnurl* Получить или оплатить через ⚡️Lnurl: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Создать криптораздачу: `/faucet <ёмкость> <на_пользователя>`
|
||||
*/tipjar* 🍯 Создать копилку: `/tipjar <ёмкость> <на_пользователя>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Введите количество между %d и %d sat."""
|
||||
enterAmountMessage = """💯 Введите количество."""
|
||||
enterUserMessage = """👤 введите пользователя."""
|
||||
errorReasonMessage = """🚫 Ошибка: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Настраиваю кошелёк для вас..."""
|
||||
startWalletCreatedMessage = """🧮 Кошелёк создан."""
|
||||
startWalletReadyMessage = """✅ *Кошелёк готов к использованию.*"""
|
||||
startWalletErrorMessage = """🚫 Ошибка инициализации кошелька. Попробуйте позже."""
|
||||
startNoUsernameMessage = """☝️ Похоже, что у вас еще нет @имени_пользователя в Telegram. Это нормально, оно не обязательно для использования этого бота. Однако, чтобы лучше использовать свой кошелек, установите имя пользователя в настройках Telegram. Затем введите /balance, чтобы бот мог обновить свои данные о вас."""
|
||||
|
||||
# BALANCE
|
||||
|
||||
balanceMessage = """👑 *Ваш баланс:* %d sat"""
|
||||
balanceErrorMessage = """🚫 Не удалось получить ваш баланс. Пожалуйста, повторите попытку позже."""
|
||||
|
||||
# TIP
|
||||
|
||||
tipDidYouReplyMessage = """Вы ответили на сообщение чтобы отправить Сатоши? Чтобы ответить на любое сообщение, нажмите правой кнопкой мыши -> Ответить на компьютере или проведите пальцем по сообщению на телефоне. Если вы хотите отправить Сатоши непосредственно другому пользователю, используйте команду /send."""
|
||||
tipInviteGroupMessage = """ℹ️ Кстати, вы можете пригласить этого бота в любую группу, чтобы можно было отправлять чаевые там."""
|
||||
tipEnterAmountMessage = """Ввели ли вы сумму?"""
|
||||
tipValidAmountMessage = """Ввели ли вы правильную сумму?"""
|
||||
tipYourselfMessage = """📖 Вы не можете отправлять самому себе."""
|
||||
tipSentMessage = """💸 %d sat отправлено %s."""
|
||||
tipReceivedMessage = """🏅 %s отправил(а) вам %d sat."""
|
||||
tipErrorMessage = """🚫 Отправка не удалась."""
|
||||
tipUndefinedErrorMsg = """пожалуйста попробуйте позжа."""
|
||||
tipHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/tip <количество> [<memo>]`
|
||||
*Пример:* `/tip 1000 Спасибо!`"""
|
||||
|
||||
# SEND
|
||||
|
||||
sendValidAmountMessage = """Ввели ли вы правильную сумму?"""
|
||||
sendUserHasNoWalletMessage = """🚫 Пользователь %s не создал кошелёк."""
|
||||
sendSentMessage = """💸 %d sat отправлено %s."""
|
||||
sendPublicSentMessage = """💸 %d sat отправил(а) %s для %s."""
|
||||
sendReceivedMessage = """🏅 %s отправил(а) вам %d sat."""
|
||||
sendErrorMessage = """🚫 Неуспешная отправка."""
|
||||
confirmSendMessage = """Вы хотите отправить Сатоши %s?\n\n💸 Amount: %d sat"""
|
||||
confirmSendAppendMemo = """\n✉️ %s"""
|
||||
sendCancelledMessage = """🚫 Отправка отменена."""
|
||||
errorTryLaterMessage = """🚫 Ошибка. Пожалуйста попробуйте позже."""
|
||||
sendSyntaxErrorMessage = """Вы ввели сумму и получателя? Вы можете использовать команду /send для отправки либо пользователям Telegram, например %s, либо на адрес Lightning, например LightningTipBot@ln.tips."""
|
||||
sendHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/send <количество> <пользователь> [<memo>]`
|
||||
*Пример:* `/send 1000 @LightningTipBot I just like the bot ❤️`
|
||||
*Пример:* `/send 1234 LightningTipBot@ln.tips`"""
|
||||
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Вы получили %d sat."""
|
||||
invoiceEnterAmountMessage = """Ввели ли вы сумму?"""
|
||||
invoiceValidAmountMessage = """Ввели ли вы правильную сумму?"""
|
||||
invoiceHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/invoice <количество> [<memo>]`
|
||||
*Пример:* `/invoice 1000 Спасибо!`"""
|
||||
|
||||
# PAY
|
||||
|
||||
paymentCancelledMessage = """🚫 Платёж отменён."""
|
||||
invoicePaidMessage = """⚡️ Платёж отправлен."""
|
||||
invoicePublicPaidMessage = """⚡️ %s отправил(а) платёж."""
|
||||
invalidInvoiceHelpMessage = """Вы ввели существующий счет в Lightning? Попробуйте /send, если вы хотите отправить пользователю Telegram или по адресу Lightning."""
|
||||
invoiceNoAmountMessage = """🚫 Невозможно оплатить инвойс без указания суммы."""
|
||||
insufficientFundsMessage = """🚫 Недостаточно средств. У вас есть %d sat, но вам нужно не менее %d sat."""
|
||||
feeReserveMessage = """⚠️ Отправка всего вашего баланса может провалиться из-за сетевых сборов. Если это не удается, попробуйте отправить немного меньше."""
|
||||
invoicePaymentFailedMessage = """🚫 Платёж не прошёл: %s"""
|
||||
invoiceUndefinedErrorMessage = """Невозможно оплатить счёт."""
|
||||
confirmPayInvoiceMessage = """Хотите ли вы отправить этот платеж?\n\n💸 Amount: %d sat"""
|
||||
confirmPayAppendMemo = """\n✉️ %s"""
|
||||
payHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/pay <инвойс>`
|
||||
*Пример:* `/pay lnbc20n1psscehd...`"""
|
||||
|
||||
# DONATE
|
||||
|
||||
donationSuccess = """🙏 Спасибо за ваше пожертвование."""
|
||||
donationErrorMessage = """🚫 О нет! Пожертвование не удалось."""
|
||||
donationProgressMessage = """🧮 Подготовка вашего пожертвования..."""
|
||||
donationFailedMessage = """🚫 Пожертвование не удалось: %s"""
|
||||
donateEnterAmountMessage = """Ввели ли вы сумму?"""
|
||||
donateValidAmountMessage = """Ввели ли вы правильную сумму?"""
|
||||
donateHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/donate <количество>`
|
||||
*Пример:* `/donate 1000`"""
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 Не удалось распознать счет Lightning или LNURL. Попробуйте отцентрировать QR-код, обрезать фотографию или увеличить масштаб."""
|
||||
photoQrRecognizedMessage = """✅ QR код:
|
||||
`%s`"""
|
||||
|
||||
# LNURL
|
||||
|
||||
lnurlReceiveInfoText = """👇 Вы можете использовать этот статический LNURL для приема платежей."""
|
||||
lnurlResolvingUrlMessage = """🧮 Уточнение адреса..."""
|
||||
lnurlGettingUserMessage = """🧮 Подготовка платежа..."""
|
||||
lnurlPaymentFailed = """🚫 Платеж не прошел: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Неверная сумма."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Сумма должна быть от %d до %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Вам нужно установить имя пользователя Telegram для получения платежей через LNURL."""
|
||||
lnurlHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/lnurl [количество] <lnurl>`
|
||||
*Пример:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """Вы хотите вывести средства?\n\n💸 Сумма: %d сб"""
|
||||
lnurlPreparingWithdraw = """🧮 Подготовка к выводу средств..."""
|
||||
lnurlWithdrawFailed = """🚫 Вывод средств не удался."""
|
||||
lnurlWithdrawCancelled = """🚫 Вывод средств отменен."""
|
||||
lnurlWithdrawSuccess = """✅ Вывод средств запрошен."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Подключение кошелька*
|
||||
|
||||
⚠️ Никогда и никому не сообщайте URL или QR-код, иначе они смогут получить доступ к вашим средствам.
|
||||
|
||||
- *BlueWallet:* Нажмите *New wallet*, *Import wallet*, *Scan or import a file*, и отсканируйте QR-код.
|
||||
- *Zeus:* Скопируйте URL ниже, нажмите *Add a new node*, *Import* (the URL), *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Не удалось связать ваш кошелек. Пожалуйста, повторите попытку позже."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
inlineQueryFaucetTitle = """🚰 Создать криптораздачу."""
|
||||
inlineQueryFaucetDescription = """Использование: @%s faucet <capacity> <per_user>"""
|
||||
inlineResultFaucetTitle = """🚰 Создать %d sat криптораздачу."""
|
||||
inlineResultFaucetDescription = """👉 Нажмите здесь, чтобы создать криптораздачу в этом чате."""
|
||||
|
||||
inlineFaucetMessage = """Нажмите ✅, чтобы забрать %d sat из этой криптораздачи от %s.
|
||||
|
||||
🚰 Осталось: %d/%d sat (отдано %d/%d пользователям)
|
||||
%s"""
|
||||
inlineFaucetEndedMessage = """🚰 Криптораздача завершена 🍺\n\n🏅 %d sat отдано %d пользователям."""
|
||||
inlineFaucetAppendMemo = """\n✉️ %s"""
|
||||
inlineFaucetCreateWalletMessage = """Напишите %s 👈 чтобы управлять своим кошельком."""
|
||||
inlineFaucetCancelledMessage = """🚫 Криптораздача отменена."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 Количество пользователей не является делителем емкости."""
|
||||
inlineFaucetInvalidAmountMessage = """🚫 Неверное количество."""
|
||||
inlineFaucetSentMessage = """🚰 %d sat отправлено %s."""
|
||||
inlineFaucetReceivedMessage = """🚰 %s отправил вам %d sat."""
|
||||
inlineFaucetHelpFaucetInGroup = """Создайте криптораздачу в группе с ботом внутри или используйте 👉 команду (/advanced для справки)."""
|
||||
inlineFaucetHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/faucet <ёмкость> <на_пользователя>`
|
||||
*Пример:* `/faucet 210 21`"""
|
||||
|
||||
# INLINE SEND
|
||||
|
||||
inlineQuerySendTitle = """💸 Отправьте платеж в чат."""
|
||||
inlineQuerySendDescription = """Использование: @%s send <количество> [<пользователь>] [<memo>]"""
|
||||
inlineResultSendTitle = """💸 Отправить %d sat."""
|
||||
inlineResultSendDescription = """👉 Нажмите, чтобы отправить %d сат в этот чат."""
|
||||
|
||||
inlineSendMessage = """Нажмите ✅ для получения платежа от %s.\n\n💸 Сумма: %d sat"""
|
||||
inlineSendAppendMemo = """\n✉️ %s"""
|
||||
inlineSendUpdateMessageAccept = """💸 %d sat отправлено с %s на %s."""
|
||||
inlineSendCreateWalletMessage = """Напишите %s 👈 чтобы управлять своим кошельком."""
|
||||
sendYourselfMessage = """📖 Вы не можете платить себе."""
|
||||
inlineSendFailedMessage = """🚫 Отправка не удалась."""
|
||||
inlineSendInvalidAmountMessage = """🚫 Сумма должна быть больше 0."""
|
||||
inlineSendBalanceLowMessage = """🚫 Ваш баланс слишком низкий."""
|
||||
|
||||
# INLINE RECEIVE
|
||||
|
||||
inlineQueryReceiveTitle = """🏅 Запросить платёж в чате."""
|
||||
inlineQueryReceiveDescription = """Использование: @%s receive <количество> [<пользователь>] [<memo>]"""
|
||||
inlineResultReceiveTitle = """🏅 Получить %d sat."""
|
||||
inlineResultReceiveDescription = """👉 Нажмите, чтобы запросить выплату в размере %d sat."""
|
||||
|
||||
inlineReceiveMessage = """Нажмите 💸 чтобы отправить Сатоши %s.\n\n💸 Количество: %d sat"""
|
||||
inlineReceiveAppendMemo = """\n✉️ %s"""
|
||||
inlineReceiveUpdateMessageAccept = """💸 %d sat отправлено от %s, получатель - %s."""
|
||||
inlineReceiveCreateWalletMessage = """Напишите %s 👈 чтобы управлять своим кошельком."""
|
||||
inlineReceiveYourselfMessage = """📖 Вы не можете платить себе."""
|
||||
inlineReceiveFailedMessage = """🚫 Получение не удалось."""
|
||||
inlineReceiveCancelledMessage = """🚫 Получение отменено."""
|
||||
|
||||
# TIPJAR
|
||||
|
||||
inlineQueryTipjarTitle = """🍯 Создать копилку."""
|
||||
inlineQueryTipjarDescription = """Использование: @%s tipjar <ёмкость> <на_пользователя>"""
|
||||
inlineResultTipjarTitle = """🍯 Создать копилку на %d sat ."""
|
||||
inlineResultTipjarDescription = """👉 Нажмите здесь, чтобы создать копилку в этом чате."""
|
||||
|
||||
inlineTipjarMessage = """Нажмите 💸 чтобы *отправить %d sat* в эту копилку, созданную %s.
|
||||
|
||||
🙏 Накоплено: *%d*/%d sat (от %d пользователей)
|
||||
%s"""
|
||||
inlineTipjarEndedMessage = """🍯 %s's копилка заполнена ⭐️\n\n🏅 %d sat отправи(л/ли) %d пользовате(ль/ли)."""
|
||||
inlineTipjarAppendMemo = """\n✉️ %s"""
|
||||
inlineTipjarCancelledMessage = """🚫 Копилка отозвана."""
|
||||
inlineTipjarInvalidPeruserAmountMessage = """🚫 Количество пользователей не является делителем емкости."""
|
||||
inlineTipjarInvalidAmountMessage = """🚫 Отправка не удалась."""
|
||||
inlineTipjarSentMessage = """🍯 %d sat отправлено в пользу %s."""
|
||||
inlineTipjarReceivedMessage = """🍯 %s отправил вам %d sat."""
|
||||
inlineTipjarHelpTipjarInGroup = """Создайте копилку в группе с ботом внутри или используйте 👉 команду (/advanced для справки)."""
|
||||
inlineTipjarHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
*Использование:* `/tipjar <ёмкость> <на_пользователя>`
|
||||
*Пример:* `/tipjar 210 21`"""
|
||||
@@ -122,12 +122,6 @@ advancedMessage = """%s
|
||||
*/faucet* 🚰 Bir fıçı oluştur: `/faucet <toplam> <kullanıcı_başına>`
|
||||
*/tipjar* 🍯 Bir tipjar oluştur: `/tipjar <capacity> <per_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 %d ve %d sat arasında bir miktar gir."""
|
||||
enterAmountMessage = """💯 Bir miktar gir."""
|
||||
enterUserMessage = """👤 Bir kullanıcı gir."""
|
||||
errorReasonMessage = """🚫 Hata: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Cüzdanın hazırlanıyor…"""
|
||||
@@ -232,6 +226,7 @@ lnurlPaymentFailed = """🚫 Ödeme başarısız: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Geçersiz miktar."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Miktar %d ve %d sat arasında olmalı."""
|
||||
lnurlNoUsernameMessage = """🚫 LNURL ödemesi almak için bir Telegram kullanıcı ismi seçmelisin."""
|
||||
lnurlEnterAmountRangeMessage = """⌨️ %d ve %d sat arasında bir miktar gir."""
|
||||
lnurlHelpText = """📖 Hoppalaa… olmadı. %s
|
||||
|
||||
*Komut:* `/lnurl [miktar] <lnurl>`
|
||||
@@ -254,7 +249,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 %s'in Fıçıdan %d sat çek.
|
||||
inlineFaucetMessage = """✅ butonuna basarak Fıçıdan %d sat çek.
|
||||
|
||||
🚰 Kalan: %d/%d sat (%d/%d çekildi)
|
||||
%s"""
|
||||
|
||||
Reference in New Issue
Block a user