Compare commits
235
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48c4bcb759 | ||
|
|
a5d8c5d7e5 | ||
|
|
0dcf4bd845 | ||
|
|
afcbca28f2 | ||
|
|
205e75d2d6 | ||
|
|
6e7886e029 | ||
|
|
00b07998e6 | ||
|
|
373b4a9752 | ||
|
|
fa46f06f2e | ||
|
|
24e321e5ed | ||
|
|
725af545ab | ||
|
|
2b09fc95dd | ||
|
|
54beceba32 | ||
|
|
70ecf335f2 | ||
|
|
d786dc58e0 | ||
|
|
c72111dfb7 | ||
|
|
902928f794 | ||
|
|
96292604c7 | ||
|
|
9522418272 | ||
|
|
a112c1b25d | ||
|
|
72e13e841d | ||
|
|
83eb185634 | ||
|
|
dedc959f94 | ||
|
|
33776f2616 | ||
|
|
545d20d043 | ||
|
|
9d876cf5d5 | ||
|
|
c6087021b7 | ||
|
|
7c95daabfd | ||
|
|
95a22401b2 | ||
|
|
a7b9506a9f | ||
|
|
c1fb07fcda | ||
|
|
5a25f07bfb | ||
|
|
b6d1ed97f1 | ||
|
|
4e812f7897 | ||
|
|
192930a289 | ||
|
|
7ed34f656b | ||
|
|
31250273b0 | ||
|
|
e70344892f | ||
|
|
39c727d3c4 | ||
|
|
02eb0716aa | ||
|
|
c706ed7aaf | ||
|
|
8c41fba277 | ||
|
|
53c384834a | ||
|
|
1e66dd6a68 | ||
|
|
b42a9ae8b4 | ||
|
|
88143b9a66 | ||
|
|
8f60cb82f3 | ||
|
|
e275b8760a | ||
|
|
01710f3385 | ||
|
|
ec319cc691 | ||
|
|
c6a064b332 | ||
|
|
615b90ab63 | ||
|
|
a7cf6f957e | ||
|
|
e9da937c75 | ||
|
|
d0da1560fa | ||
|
|
113fc02b28 | ||
|
|
1459fcb68e | ||
|
|
3d3d7ab2f6 | ||
|
|
fdb58a7f2b | ||
|
|
a9fecc1e8f | ||
|
|
d65d6aad28 | ||
|
|
95c733459d | ||
|
|
9fe0d776c7 | ||
|
|
25dc9d7b34 | ||
|
|
01423827b7 | ||
|
|
f1df1e6377 | ||
|
|
1e5f7b1169 | ||
|
|
9c6062f317 | ||
|
|
fc7247c72a | ||
|
|
c23d69e8f1 | ||
|
|
35d5ed8d8e | ||
|
|
07ccc6cc28 | ||
|
|
2ef798e56a | ||
|
|
24e4212a93 | ||
|
|
6851badfab | ||
|
|
cbedc5c147 | ||
|
|
373ee844da | ||
|
|
151ed39b04 | ||
|
|
24108f6a1f | ||
|
|
737ab115bd | ||
|
|
13957342df | ||
|
|
fe1a921440 | ||
|
|
39ff25beca | ||
|
|
ec15f26c13 | ||
|
|
0218191793 | ||
|
|
5065f5af86 | ||
|
|
6aca41835d | ||
|
|
6b746447e5 | ||
|
|
ca60b271fd | ||
|
|
1b720b498c | ||
|
|
2066470cba | ||
|
|
73ada1f25b | ||
|
|
43a77fd1b2 | ||
|
|
f968310902 | ||
|
|
32a5a7c264 | ||
|
|
776de88041 | ||
|
|
192a100f8d | ||
|
|
b796db1979 | ||
|
|
eb07cdf117 | ||
|
|
9f1ce26d6e | ||
|
|
0ce42e8f1f | ||
|
|
46d77de38e | ||
|
|
09d3af411e | ||
|
|
5414c82339 | ||
|
|
2edc2953dc | ||
|
|
2bc9555b53 | ||
|
|
47ef5baee3 | ||
|
|
78eadf1a0e | ||
|
|
6aa05c8faa | ||
|
|
8f8644a1d2 | ||
|
|
f9aed70869 | ||
|
|
036ac12f41 | ||
|
|
67cff58c63 | ||
|
|
4730c94c84 | ||
|
|
e53ef94306 | ||
|
|
a9f2728c93 | ||
|
|
657fc7af1d | ||
|
|
1b24072020 | ||
|
|
d912541391 | ||
|
|
72381d0071 | ||
|
|
a644c465cd | ||
|
|
bc0d3df897 | ||
|
|
fa234d4073 | ||
|
|
dd88c93474 | ||
|
|
2469898f9f | ||
|
|
ee656dc5f0 | ||
|
|
3eba0de851 | ||
|
|
f8fadb1729 | ||
|
|
6b5e30dbe4 | ||
|
|
72ef490538 | ||
|
|
7e2404eaf5 | ||
|
|
64f9492af2 | ||
|
|
f85ec34bcc | ||
|
|
8b40253169 | ||
|
|
91d38b5bb4 | ||
|
|
a59a7c226d | ||
|
|
4b620186f1 | ||
|
|
f313b5cdbe | ||
|
|
179d40178c | ||
|
|
15d711a6fd | ||
|
|
a4f5b21f1d | ||
|
|
307d9cd873 | ||
|
|
0f6c37a40c | ||
|
|
9e4b612c26 | ||
|
|
1815bcfaf9 | ||
|
|
6299adf633 | ||
|
|
5b93d43bc5 | ||
|
|
0cfb693619 | ||
|
|
1ea9268698 | ||
|
|
f50e6ced71 | ||
|
|
1b922c03a9 | ||
|
|
f6768b72ea | ||
|
|
236b095bbe | ||
|
|
a0799b1b32 | ||
|
|
38251600f9 | ||
|
|
aaa8a3cc19 | ||
|
|
25d9b8af3b | ||
|
|
ba6bf0a317 | ||
|
|
0abe56dfba | ||
|
|
7c8ba7895d | ||
|
|
eeb9d5224e | ||
|
|
79112717cf | ||
|
|
4a9a77d5f1 | ||
|
|
4ba892908b | ||
|
|
3891c70344 | ||
|
|
6e6c9e02a4 | ||
|
|
488fab7f9f | ||
|
|
8f569ed4c3 | ||
|
|
3f26f0b44f | ||
|
|
1f25cc6ded | ||
|
|
69b0dd5a4a | ||
|
|
e1d858752f | ||
|
|
88bbd4d2cf | ||
|
|
8c4adb4dd4 | ||
|
|
9290f55fa4 | ||
|
|
0653498e0f | ||
|
|
dd57247266 | ||
|
|
051174bd1c | ||
|
|
5eaf380e91 | ||
|
|
fb73c1fe08 | ||
|
|
4a03724540 | ||
|
|
5725a0c9c0 | ||
|
|
d8a98ad433 | ||
|
|
11edce049e | ||
|
|
e4833bd9c6 | ||
|
|
51c410c045 | ||
|
|
f0385128db | ||
|
|
c90cfd9d8a | ||
|
|
97b6e8f043 | ||
|
|
8da9e0c38c | ||
|
|
fd9ad39b0c | ||
|
|
bb00253122 | ||
|
|
10c9121cc7 | ||
|
|
236097a461 | ||
|
|
22d4ab284c | ||
|
|
3a2c5b2c51 | ||
|
|
c7212131fa | ||
|
|
88fdb4de9b | ||
|
|
693f12470c | ||
|
|
887751cb0f | ||
|
|
08c7ff5113 | ||
|
|
7c77d268f6 | ||
|
|
61bc3710c0 | ||
|
|
a880d7b044 | ||
|
|
8c7c22b0d8 | ||
|
|
94eff98f60 | ||
|
|
6a5f09fa18 | ||
|
|
808a5a3b72 | ||
|
|
903cc3c2e2 | ||
|
|
f6ef7933f5 | ||
|
|
48fce72559 | ||
|
|
31caa37657 | ||
|
|
a9b9d0bfdd | ||
|
|
a7a7968d09 | ||
|
|
7e532f3f01 | ||
|
|
4d5731bf51 | ||
|
|
5784126bbd | ||
|
|
af21ad4bea | ||
|
|
4830928352 | ||
|
|
167b581d3e | ||
|
|
2c51662a75 | ||
|
|
fbbe18d7a7 | ||
|
|
e3ba16f5d1 | ||
|
|
39ed394984 | ||
|
|
1b97544ad5 | ||
|
|
7c33234d91 | ||
|
|
f23e4098e3 | ||
|
|
1a073b339b | ||
|
|
0653b82c10 | ||
|
|
4a9dcc9601 | ||
|
|
34d951ee85 | ||
|
|
8af08357d0 | ||
|
|
a19fa50bb8 | ||
|
|
079e490cac | ||
|
|
acf0cb5af6 |
@@ -29,7 +29,7 @@ After the configuration (see below), start it using the command
|
||||
|
||||
### Configuration
|
||||
|
||||
You need to edit `config.yaml` before starting the bot.
|
||||
You need to edit `config.yaml` before you can start the bot.
|
||||
|
||||
#### Create a Telegram bot
|
||||
|
||||
@@ -39,7 +39,7 @@ First, create a new Telegram bot by starting a conversation with the [@BotFather
|
||||
|
||||
You can either use your own LNbits instance (recommended) or create an account at [lnbits.com](https://lnbits.com/) to use their custodial service (easy).
|
||||
|
||||
1. Create a wallet in LNbits (`lnbits_url`).
|
||||
1. Create a wallet in LNbits (reachable by the bot via `lnbits_url`).
|
||||
2. Get the **Admin key** in the API Info tab of your user (`lnbits_admin_key`).
|
||||
3. Enable the User Manager extension.
|
||||
4. Get the **Admin ID** of the User Manager (`lnbits_admin_id`).
|
||||
@@ -52,26 +52,53 @@ You can either use your own LNbits instance (recommended) or create an account a
|
||||
|
||||
#### More configuration
|
||||
|
||||
- `webhook_server`: URL that can reach the bot. This is used for creating webhooks with LNbits to receive notifications about payments (optional).
|
||||
- `db_path`: User database file path.
|
||||
- `transactions_path`: Transaction log file path.
|
||||
- `message_dispose_duration`: Duration in seconds after which commands will be deleted from channel (only if the bot is channel admin).
|
||||
- `transactions_path`: Transaction database file path.
|
||||
- `buntdb_path`: Object storage database file path.
|
||||
- `lnbits_webhook_server`: URL that lnbits can reach the bot with. This is used for creating webhooks from LNbits to receive notifications about payments (optional).
|
||||
- `message_dispose_duration`: Duration in seconds after which `/tip` are deleted from a channel (only if the bot is channel admin).
|
||||
- `http_proxy` uses a proxy for all LNURL-related outbound requests (optional).
|
||||
- `lnurl_public_host_name` is the public URL of your lnbits/LndHub (for BlueWallet/Zap support, optional).
|
||||
- `lnurl_server` is the public URL for inbound LNURL payments and your lightning address host (optional).
|
||||
|
||||
## Features
|
||||
|
||||
### Commands
|
||||
#### Commands
|
||||
|
||||
```
|
||||
/tip 🏅 Reply to a message to tip it: /tip <amount> [<memo>]
|
||||
/balance 👑 Check your balance: /balance
|
||||
/send 💸 Send funds to a user: /send <amount> <@username> [<memo>]
|
||||
/invoice ⚡️ Create a Lightning invoice to receive payments: /invoice <amount> [<memo>]
|
||||
/pay ⚡️ Pay a Lightning invoice: /pay <invoice>
|
||||
/send 💸 Send funds to a user: /send <amount> <@user> or <user@domain.com> [<memo>]
|
||||
/invoice ⚡️ Receive over Lightning: /invoice <amount> [<memo>]
|
||||
/pay ⚡️ Pay over Lightning: /pay <invoice>
|
||||
/help 📖 Read this help.
|
||||
/info 📚 More info.
|
||||
/donate 🙏 Donate to @LightningTipBot: /donate <amount>
|
||||
/advanced 🤖 Read the advanced help.
|
||||
/basics 📚 More info.
|
||||
/donate ❤️ Donate to the project: /donate <amount>
|
||||
```
|
||||
|
||||
#### Advanced commands
|
||||
|
||||
```
|
||||
/link 🔗 Link your wallet to BlueWallet or Zeus
|
||||
/lnurl ⚡️ Lnurl receive or pay: /lnurl or /lnurl <lnurl>
|
||||
```
|
||||
|
||||
### Inline commands
|
||||
```
|
||||
send 💸 Send sats to chat: @LightningTipBot send <amount> [<memo>]
|
||||
```
|
||||
|
||||
📖 You can use inline commands in every chat, even in private conversations. Wait a second after entering an inline command and click the result, don't press enter.
|
||||
|
||||
### Inline send
|
||||
|
||||
You can use inline commands to send payments to anyone who can read your messages, even inside private chats and group chat in which the bot isn't part of. For that, you need to trigger an [inline command](https://core.telegram.org/bots/inline). Here is how it works: Enter the name of the bot (`@LightningTipBot`) and the command you want to trigger (`send 13 Hi friend!`). When the result pops up above the text field, click it to send it to the chat. Do not press enter.
|
||||
|
||||
<p align="center">
|
||||
<img alt="Send sats inside any chat, including private conversations and groups." src="resources/inline_send.png" >
|
||||
</p>
|
||||
|
||||
### Live tooltips
|
||||
|
||||
The bot replies to a tipped message to indicate to all participants how many and what amount of tips a post has received. This tooltip will be updated as new tips are given to a post.
|
||||
@@ -80,9 +107,18 @@ The bot replies to a tipped message to indicate to all participants how many and
|
||||
<img alt="How to set up a lnbits wallet and the User Manager extension." src="resources/tooltips.png" >
|
||||
</p>
|
||||
|
||||
|
||||
### LNURL server
|
||||
|
||||
Users can send and receive via . For this to work, you need to set the `lnurl_public_server` in `config.yaml`. The bot will then host a LNURL endpoint at `.well-known/lnurlp/username` which handles the data exchange with other wallets. You can set `http_proxy` in `config.yaml` to send outbound requests only via an HTTP proxy.
|
||||
|
||||
### Send and receive via Lightning Address
|
||||
|
||||
Every user has a [Lightning Address](https://lightningaddress.com/) a la `username@host.com` with which they can send to via `/send <amount> <user@domain.com>` and receive from other wallets.
|
||||
|
||||
### Link to BlueWallet or Zap
|
||||
|
||||
Every user can link their wallet to an external app like [Bluewallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/) by using the command `/link`. If you host the bot, you will have to enable the LndHub extension in LNbits. You also need to edit the `lnbits_public_url` entry in `config.yaml` accordingly to an address that can be reached.
|
||||
Every user can link their wallet to an external app like [Bluewallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/) by using the command `/link`. If you host the bot, you will have to enable the LndHub extension in LNbits. You also need to edit the `lnbits_public_url` entry in `config.yaml` accordingly to an address that can be reached by the user's wallet (Tor should be fine as well).
|
||||
|
||||
<p align="center">
|
||||
<img alt="QR code payment example." src="resources/lndhub.png" >
|
||||
@@ -106,3 +142,4 @@ To minimize the clutter all the heavy tipping can cause in a group chat, the bot
|
||||
- [telebot](https://github.com/tucnak/telebot) – A Telegram bot framework in Go.
|
||||
- [gozxing](https://github.com/makiuchi-d/gozxing) – barcode image processing library in Go.
|
||||
- [ln-decodepay](https://github.com/fiatjaf/ln-decodepay) – Lightning Network BOLT11 invoice decoder.
|
||||
- [go-lnurl](https://github.com/fiatjaf/go-lnurl) - Helpers for building lnurl support into services.
|
||||
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func getArgumentFromCommand(input string, which int) (output string, err error) {
|
||||
if len(strings.Split(input, " ")) < which+1 {
|
||||
return "", errors.New("Message doesn't contain enough arguments")
|
||||
}
|
||||
output = strings.Split(input, " ")[which]
|
||||
return output, nil
|
||||
}
|
||||
|
||||
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, errors.New(errmsg)
|
||||
}
|
||||
amount, err = getAmount(input)
|
||||
return amount, nil
|
||||
}
|
||||
|
||||
func getAmount(input string) (amount int, err error) {
|
||||
amount, err = strconv.Atoi(strings.Split(input, " ")[1])
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if amount < 1 {
|
||||
errmsg := "Error: Amount must be greater than 0"
|
||||
// log.Errorln(errmsg)
|
||||
return 0, errors.New(errmsg)
|
||||
}
|
||||
return amount, err
|
||||
}
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot TipBot) balanceHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
// reply only in private message
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
}
|
||||
// first check whether the user is initialized
|
||||
fromUser, err := GetUser(m.Sender, bot)
|
||||
if err != nil {
|
||||
log.Errorf("[/balance] Error: %s", err)
|
||||
return
|
||||
}
|
||||
if !fromUser.Initialized {
|
||||
bot.startHandler(m)
|
||||
return
|
||||
}
|
||||
|
||||
usrStr := GetUserStr(m.Sender)
|
||||
balance, err := bot.GetUserBalance(m.Sender)
|
||||
if err != nil {
|
||||
log.Errorf("[/balance] Error fetching %s's balance: %s", usrStr, err)
|
||||
bot.telegram.Send(m.Sender, "🚫 Error fetching your balance. Please try again later.")
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[/balance] %s's balance: %d sat\n", usrStr, balance)
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf("👑 *Your balance:* %d sat", balance))
|
||||
return
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type TipBot struct {
|
||||
database *gorm.DB
|
||||
logger *gorm.DB
|
||||
telegram *telebot.Bot
|
||||
client *lnbits.Client
|
||||
tips map[int][]*Message
|
||||
}
|
||||
|
||||
var (
|
||||
paymentConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelPay = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_pay")
|
||||
btnPay = paymentConfirmationMenu.Data("✅ Pay", "confirm_pay")
|
||||
sendConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelSend = sendConfirmationMenu.Data("🚫 Cancel", "cancel_send")
|
||||
btnSend = sendConfirmationMenu.Data("✅ Send", "confirm_send")
|
||||
|
||||
botWalletInitialisation = sync.Once{}
|
||||
telegramHandlerRegistration = sync.Once{}
|
||||
)
|
||||
|
||||
// NewBot migrates data and creates a new bot
|
||||
func NewBot() TipBot {
|
||||
db, txLogger := migration()
|
||||
return TipBot{
|
||||
database: db,
|
||||
logger: txLogger,
|
||||
tips: make(map[int][]*Message, 0),
|
||||
}
|
||||
}
|
||||
|
||||
// newTelegramBot will create a new telegram bot.
|
||||
func newTelegramBot() *tb.Bot {
|
||||
tgb, err := tb.NewBot(tb.Settings{
|
||||
Token: Configuration.ApiKey,
|
||||
Poller: &tb.LongPoller{Timeout: 60 * time.Second},
|
||||
ParseMode: tb.ModeMarkdown,
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return tgb
|
||||
}
|
||||
|
||||
// initBotWallet will create / initialize the bot wallet
|
||||
// todo -- may want to derive user wallets from this specific bot wallet (master wallet), since lnbits usermanager extension is able to do that.
|
||||
func (bot TipBot) initBotWallet() error {
|
||||
botWalletInitialisation.Do(func() {
|
||||
err := bot.initWallet(bot.telegram.Me)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[initBotWallet] Could not initialize bot wallet: %s", err.Error()))
|
||||
return
|
||||
}
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// registerTelegramHandlers will register all telegram handlers.
|
||||
func (bot TipBot) registerTelegramHandlers() {
|
||||
telegramHandlerRegistration.Do(func() {
|
||||
// Set up handlers
|
||||
var endpointHandler = map[string]interface{}{
|
||||
"/tip": bot.tipHandler,
|
||||
"/pay": bot.confirmPaymentHandler,
|
||||
"/invoice": bot.invoiceHandler,
|
||||
"/balance": bot.balanceHandler,
|
||||
"/start": bot.startHandler,
|
||||
"/send": bot.confirmSendHandler,
|
||||
"/help": bot.helpHandler,
|
||||
"/info": bot.infoHandler,
|
||||
"/donate": bot.donationHandler,
|
||||
"/advanced": bot.advancedHelpHandler,
|
||||
"/link": bot.lndhubHandler,
|
||||
tb.OnPhoto: bot.privatePhotoHandler,
|
||||
tb.OnText: bot.anyTextHandler,
|
||||
}
|
||||
// assign handler to endpoint
|
||||
for endpoint, handler := range endpointHandler {
|
||||
log.Debugf("Registering: %s", endpoint)
|
||||
bot.telegram.Handle(endpoint, handler)
|
||||
|
||||
// if the endpoint is a string command (not photo etc)
|
||||
if strings.HasPrefix(endpoint, "/") {
|
||||
// register upper case versions as well
|
||||
bot.telegram.Handle(strings.ToUpper(endpoint), handler)
|
||||
}
|
||||
}
|
||||
|
||||
// button handlers
|
||||
// for /pay
|
||||
bot.telegram.Handle(&btnPay, bot.payHandler)
|
||||
bot.telegram.Handle(&btnCancelPay, bot.cancelPaymentHandler)
|
||||
// for /send
|
||||
bot.telegram.Handle(&btnSend, bot.sendHandler)
|
||||
bot.telegram.Handle(&btnCancelSend, bot.cancelSendHandler)
|
||||
})
|
||||
}
|
||||
|
||||
// Start will initialize the telegram bot and lnbits.
|
||||
func (bot TipBot) Start() {
|
||||
// set up lnbits api
|
||||
bot.client = lnbits.NewClient(Configuration.LnbitsKey, Configuration.LnbitsUrl)
|
||||
// set up telebot
|
||||
bot.telegram = newTelegramBot()
|
||||
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())
|
||||
}
|
||||
bot.registerTelegramHandlers()
|
||||
lnbits.NewWebhook(Configuration.WebhookServer, bot.telegram, bot.client, bot.database)
|
||||
bot.telegram.Start()
|
||||
}
|
||||
@@ -6,10 +6,12 @@
|
||||
4 - Paste this:
|
||||
|
||||
help - Read the help.
|
||||
balance - Check your balance.
|
||||
tip - Reply to a message to tip. Example: /tip 50
|
||||
send - Send funds to a Telegram user. Example: /send 100 @LightningTipBot
|
||||
invoice - Create a Lightning invoice to receive payments. Example: /invoice 1000
|
||||
pay - Pay a Lightning invoice. Example: /pay lnbc10n1ps...
|
||||
donate - Donate to the project: Example: /donate 1000
|
||||
balance - Check balance.
|
||||
tip - Reply to a message to tip: /tip 50
|
||||
send - Send funds to a user: /send 100 @LightningTipBot
|
||||
invoice - Receive with Lightning: /invoice 1000
|
||||
pay - Pay with Lightning: /pay lnbc10n1ps...
|
||||
donate - Donate: /donate 1000
|
||||
faucet - Create a faucet: /faucet 2100 21
|
||||
tipjar - Create a tipjar: /tipjar 100 10
|
||||
advanced - Advanced help
|
||||
@@ -1,22 +0,0 @@
|
||||
package main
|
||||
|
||||
import "github.com/jinzhu/configor"
|
||||
|
||||
var Configuration = struct {
|
||||
AdminKey string `json:"lnbits_admin_id" yaml:"lnbits_admin_id"`
|
||||
LnbitsKey string `json:"lnbits_admin_key" yaml:"lnbits_admin_key"`
|
||||
LnbitsUrl string `json:"lnbits_url" yaml:"lnbits_url"`
|
||||
LnbitsPublicUrl string `json:"lnbits_public_url" yaml:"lnbits_public_url"`
|
||||
WebhookServer string `json:"webhook_server" yaml:"webhook_server"`
|
||||
ApiKey string `json:"telegram_api_key" yaml:"telegram_api_key"`
|
||||
DbPath string `json:"db_path" yaml:"db_path"`
|
||||
TransactionsPath string `json:"transactions_path" yaml:"transactions_path"`
|
||||
MessageDisposeDuration int64 `json:"message_dispose_duration" yaml:"message_dispose_duration"`
|
||||
}{}
|
||||
|
||||
func init() {
|
||||
err := configor.Load(&Configuration, "config.yaml")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
+19
-9
@@ -1,9 +1,19 @@
|
||||
telegram_api_key: "1234"
|
||||
webhook_server: "http://0.0.0.0:1234"
|
||||
lnbits_url: "http://127.0.0.1:1234"
|
||||
lnbits_public_url: "http://*.onion:1234"
|
||||
lnbits_admin_key: "1234"
|
||||
lnbits_admin_id: "3212"
|
||||
db_path: "data/bot.db"
|
||||
transactions_path: "data/transactions.db"
|
||||
message_dispose_duration: 10
|
||||
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"
|
||||
lnbits:
|
||||
url: "http://127.0.0.1:5000"
|
||||
admin_key: "1234"
|
||||
admin_id: "1234"
|
||||
webhook_server: "http://0.0.0.0:5588"
|
||||
lnbits_public_url: "link.mylnurl.com"
|
||||
database:
|
||||
db_path: "data/bot.db"
|
||||
buntdb_path: "data/bunt.db"
|
||||
transactions_path: "data/transactions.db"
|
||||
shop_buntdb_path: "data/shop.db"
|
||||
|
||||
-73
@@ -1,73 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func migration() (db *gorm.DB, txLogger *gorm.DB) {
|
||||
txLogger, err := gorm.Open(sqlite.Open(Configuration.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
if err != nil {
|
||||
panic("Initialize orm failed.")
|
||||
}
|
||||
|
||||
orm, err := gorm.Open(sqlite.Open(Configuration.DbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
if err != nil {
|
||||
panic("Initialize orm failed.")
|
||||
}
|
||||
|
||||
err = orm.AutoMigrate(&lnbits.User{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = txLogger.AutoMigrate(&Transaction{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return orm, txLogger
|
||||
}
|
||||
|
||||
// GetUser from telegram user. Update the user if user information changed.
|
||||
func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
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's info from database.", GetUserStr(u))
|
||||
log.Warnln(errmsg)
|
||||
return user, tx.Error
|
||||
}
|
||||
defer func() {
|
||||
user.Wallet.Client = bot.client
|
||||
}()
|
||||
var err error
|
||||
go func() {
|
||||
if !reflect.DeepEqual(u, user.Telegram) {
|
||||
// update possibly changed user details in database
|
||||
user.Telegram = u
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
log.Warnln(fmt.Sprintf("[UpdateUserRecord] %s", err.Error()))
|
||||
}
|
||||
}
|
||||
}()
|
||||
return user, err
|
||||
}
|
||||
|
||||
func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
|
||||
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.Debugf("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
|
||||
return nil
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
// PLEASE DO NOT CHANGE THE CODE IN THIS FILE
|
||||
// YOU MIGHT BREAK DONATIONS TO THE ORIGINAL PROJECT
|
||||
// THE DEVELOPMENT OF LIGHTNINGTIPBOT RELIES ON DONATIONS
|
||||
// IF YOU USE THIS PROJECT, LEAVE THIS CODE ALONE
|
||||
|
||||
var (
|
||||
donationSuccess = "🙏 Thank you for your donation."
|
||||
donationErrorMessage = "🚫 Oh no. Donation failed."
|
||||
donationFailedMessage = "🚫 Donation failed: %s"
|
||||
donateEnterAmountMessage = "Did you enter an amount?"
|
||||
donateValidAmountMessage = "Did you enter a valid amount?"
|
||||
donateHelpText = "📖 Oops, that didn't work. %s\n\n" +
|
||||
"*Usage:* `/donate <amount>`\n" +
|
||||
"*Example:* `/donate 1000`"
|
||||
endpoint string
|
||||
)
|
||||
|
||||
func init() {
|
||||
var sb strings.Builder
|
||||
_, err := io.Copy(&sb, rot13Reader{strings.NewReader("uggcf://ya.gvcf/qbangr/%q?sebz=%f&obg=%f")})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
endpoint = sb.String()
|
||||
}
|
||||
|
||||
func helpDonateUsage(errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(donateHelpText, fmt.Sprintf("%s", errormsg))
|
||||
} else {
|
||||
return fmt.Sprintf(donateHelpText, "")
|
||||
}
|
||||
}
|
||||
|
||||
func (bot TipBot) donationHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
|
||||
if len(strings.Split(m.Text, " ")) < 2 {
|
||||
bot.telegram.Send(m.Sender, helpDonateUsage(donateEnterAmountMessage))
|
||||
return
|
||||
}
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if amount < 1 {
|
||||
bot.telegram.Send(m.Sender, helpDonateUsage(donateValidAmountMessage))
|
||||
return
|
||||
}
|
||||
|
||||
// command is valid
|
||||
|
||||
// get invoice
|
||||
resp, err := http.Get(fmt.Sprintf(endpoint, amount, GetUserStr(m.Sender), GetUserStr(bot.telegram.Me)))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.telegram.Send(m.Sender, donationErrorMessage)
|
||||
return
|
||||
}
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.telegram.Send(m.Sender, donationErrorMessage)
|
||||
return
|
||||
}
|
||||
|
||||
// send donation invoice
|
||||
user, err := GetUser(m.Sender, bot)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// bot.telegram.Send(user.Telegram, string(body))
|
||||
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: string(body)}, *user.Wallet)
|
||||
if err != nil {
|
||||
userStr := GetUserStr(m.Sender)
|
||||
errmsg := fmt.Sprintf("[/donate] Donation failed for user %s: %s", userStr, err)
|
||||
log.Errorln(errmsg)
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf(donationFailedMessage, err))
|
||||
return
|
||||
}
|
||||
bot.telegram.Send(m.Sender, donationSuccess)
|
||||
|
||||
}
|
||||
|
||||
type rot13Reader struct {
|
||||
r io.Reader
|
||||
}
|
||||
|
||||
func (rot13 rot13Reader) Read(b []byte) (int, error) {
|
||||
n, err := rot13.r.Read(b)
|
||||
for i := 0; i < n; i++ {
|
||||
switch {
|
||||
case b[i] >= 65 && b[i] <= 90:
|
||||
if b[i] <= 77 {
|
||||
b[i] = b[i] + 13
|
||||
} else {
|
||||
b[i] = b[i] - 13
|
||||
}
|
||||
case b[i] >= 97 && b[i] <= 122:
|
||||
if b[i] <= 109 {
|
||||
b[i] = b[i] + 13
|
||||
} else {
|
||||
b[i] = b[i] - 13
|
||||
}
|
||||
}
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (bot TipBot) parseCmdDonHandler(m *tb.Message) error {
|
||||
arg := ""
|
||||
if strings.HasPrefix(strings.ToLower(m.Text), "/send") {
|
||||
arg, _ = getArgumentFromCommand(m.Text, 2)
|
||||
if arg != "@"+bot.telegram.Me.Username {
|
||||
return fmt.Errorf("err")
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(strings.ToLower(m.Text), "/tip") {
|
||||
arg = GetUserStr(m.ReplyTo.Sender)
|
||||
if arg != "@"+bot.telegram.Me.Username {
|
||||
return fmt.Errorf("err")
|
||||
}
|
||||
}
|
||||
if arg == "@LightningTipBot" || len(arg) < 1 {
|
||||
return fmt.Errorf("err")
|
||||
}
|
||||
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
_, err = io.Copy(&sb, rot13Reader{strings.NewReader("Vg ybbxf yvxr lbh'er znxvat n qbangvba. V'z ebhgvat guvf gb gur bevtvany cebwrpg.")})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
donationInterceptMessage := sb.String()
|
||||
|
||||
bot.telegram.Send(m.Sender, donationInterceptMessage)
|
||||
m.Text = fmt.Sprintf("/donate %d", amount)
|
||||
bot.donationHandler(m)
|
||||
// returning nil here will abort the parent handler (/pay or /tip)
|
||||
return nil
|
||||
}
|
||||
@@ -3,15 +3,29 @@ module github.com/LightningTipBot/LightningTipBot
|
||||
go 1.15
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v0.3.1
|
||||
github.com/btcsuite/btcd v0.20.1-beta.0.20200515232429-9f0179fd2c46 // indirect
|
||||
github.com/eko/gocache v1.2.0
|
||||
github.com/fiatjaf/go-lnurl v1.8.4
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0
|
||||
github.com/gorilla/mux v1.8.0
|
||||
github.com/imroc/req v0.3.0
|
||||
github.com/jinzhu/configor v1.2.1
|
||||
github.com/liyue201/goqr v0.0.0-20200803022322-df443203d4ea
|
||||
github.com/makiuchi-d/gozxing v0.0.2
|
||||
github.com/sirupsen/logrus v1.2.0
|
||||
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
|
||||
gopkg.in/tucnak/telebot.v2 v2.3.5
|
||||
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
|
||||
gorm.io/driver/sqlite v1.1.4
|
||||
gorm.io/gorm v1.21.12
|
||||
)
|
||||
|
||||
// replace gopkg.in/lightningtipbot/telebot.v2 => ../telebot
|
||||
|
||||
@@ -1,19 +1,49 @@
|
||||
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
git.schwanenlied.me/yawning/bsaes.git v0.0.0-20180720073208-c0276d75487e/go.mod h1:BWqTsj8PgcPriQJGl7el20J/7TuT1d/hSyFDXMEpoEo=
|
||||
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
|
||||
github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ=
|
||||
github.com/NebulousLabs/fastrand v0.0.0-20181203155948-6fb6489aac4e/go.mod h1:Bdzq+51GR4/0DIhaICZEOm+OHvXGwwB2trKZ8B4Y6eQ=
|
||||
github.com/NebulousLabs/go-upnp v0.0.0-20180202185039-29b680b06c82/go.mod h1:GbuBk21JqF+driLX3XtJYNZjGa45YDoa9IqCTzNSfEc=
|
||||
github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE=
|
||||
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
|
||||
github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
|
||||
github.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
|
||||
github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo=
|
||||
github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI=
|
||||
github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g=
|
||||
github.com/XiaoMi/pegasus-go-client v0.0.0-20210427083443-f3b6b08bc4c2 h1:pami0oPhVosjOu/qRHepRmdjD6hGILF7DBr+qQZeP10=
|
||||
github.com/XiaoMi/pegasus-go-client v0.0.0-20210427083443-f3b6b08bc4c2/go.mod h1:jNIx5ykW1MroBuaTja9+VpglmaJOUzezumfhLlER3oY=
|
||||
github.com/Yawning/aez v0.0.0-20180114000226-4dad034d9db2/go.mod h1:9pIqrY6SXNL8vjRQE5Hd/OL5GyK/9MrGUWs87z/eFfk=
|
||||
github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da/go.mod h1:eHEWzANqSiWQsof+nXEI9bUVUyV6F53Fp89EuCh2EAA=
|
||||
github.com/aead/siphash v1.0.1 h1:FwHfE/T45KPKYuuSAKyyvE+oPWcaQ+CUmFW0bPlM+kg=
|
||||
github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII=
|
||||
github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c=
|
||||
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
|
||||
github.com/allegro/bigcache/v2 v2.2.5 h1:mRc8r6GQjuJsmSKQNPsR5jQVXc8IJ1xsW5YXUYMLfqI=
|
||||
github.com/allegro/bigcache/v2 v2.2.5/go.mod h1:FppZsIO+IZk7gCuj5FiIDHGygD9xvWQcqg1uIPMb6tY=
|
||||
github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ=
|
||||
github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ=
|
||||
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
|
||||
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
|
||||
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
|
||||
github.com/aryann/difflib v0.0.0-20170710044230-e206f873d14a/go.mod h1:DAHtR1m6lCRdSC2Tm3DSWRPvIPr6xNKyeHdqDQSQT+A=
|
||||
github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY=
|
||||
github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQwij/eHl5CU=
|
||||
github.com/aws/aws-sdk-go v1.27.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
|
||||
github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g=
|
||||
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
|
||||
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
|
||||
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b h1:L/QXpzIa3pOvUGt1D1lA5KjYhPBAN/3iWdP7xeFS9F0=
|
||||
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA=
|
||||
github.com/btcsuite/btcd v0.0.0-20190629003639-c26ffa870fd8/go.mod h1:3J08xEfcugPacsc34/LKRU2yO7YmuT8yt28J8k2+rrI=
|
||||
github.com/btcsuite/btcd v0.0.0-20190824003749-130ea5bddde3/go.mod h1:3J08xEfcugPacsc34/LKRU2yO7YmuT8yt28J8k2+rrI=
|
||||
github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ=
|
||||
@@ -53,53 +83,184 @@ 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=
|
||||
github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM=
|
||||
github.com/cenkalti/backoff/v4 v4.1.0 h1:c8LkOFQTzuO0WBM/ae5HdGQuZPfPxp7lqBRwQRm4fSc=
|
||||
github.com/cenkalti/backoff/v4 v4.1.0/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw=
|
||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||
github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko=
|
||||
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
|
||||
github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY=
|
||||
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/clbanning/x2j v0.0.0-20191024224557-825249438eec/go.mod h1:jMjuTZXRI4dUb/I5gc9Hdhagfvm9+RyrPryS/auMzxE=
|
||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||
github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8=
|
||||
github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI=
|
||||
github.com/coocood/freecache v1.1.1 h1:uukNF7QKCZEdZ9gAV7WQzvh0SbjwdMF6m3x3rxEkaPc=
|
||||
github.com/coocood/freecache v1.1.1/go.mod h1:OKrEjkGVoxZhyWAJoeFi5BMLUJm2Tit0kpGkIr7NGYY=
|
||||
github.com/coreos/bbolt v1.3.3 h1:n6AiVyVRKQFNb6mJlwESEvvLoDyiTzXX7ORAUlkeBdY=
|
||||
github.com/coreos/bbolt v1.3.3/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
|
||||
github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
|
||||
github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
|
||||
github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||
github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
|
||||
github.com/davecgh/go-spew v0.0.0-20151105211317-5215b55f46b2/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgraph-io/ristretto v0.0.3 h1:jh22xisGBjrEVnRZ1DVTpBVQm0Xndu8sMl0CWDzSIBI=
|
||||
github.com/dgraph-io/ristretto v0.0.3/go.mod h1:KPxhHT9ZxKefz+PCeOGsrHpl1qZ7i70dGTu2u+Ahh6E=
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
|
||||
github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA=
|
||||
github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
|
||||
github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZgvJUkLughtfhJv5dyTYa91l1fOUCrgjqmcifM=
|
||||
github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
|
||||
github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs=
|
||||
github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU=
|
||||
github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I=
|
||||
github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M=
|
||||
github.com/eko/gocache v1.2.0 h1:SCtTs65qMXjhdtu62yHPCQuzdMkQjP+fQmkNrVutkRw=
|
||||
github.com/eko/gocache v1.2.0/go.mod h1:6u8/2bnr+nOf87mRXWS710rqNNZUECF4CGsPNnsoJ78=
|
||||
github.com/elazarl/goproxy v0.0.0-20170405201442-c4fc26588b6e/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc=
|
||||
github.com/emicklei/go-restful v0.0.0-20170410110728-ff4f55a20633/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs=
|
||||
github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4safvEdbitLhGGK48rN6g=
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||
github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk=
|
||||
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
|
||||
github.com/fiatjaf/go-lnurl v1.4.0 h1:hVFEEJD2A9D6ojEcqLyD54CM2ZJ9Tzs2jNKw/GNq52A=
|
||||
github.com/fiatjaf/go-lnurl v1.4.0/go.mod h1:BqA8WXAOzntF7Z3EkVO7DfP4y5rhWUmJ/Bu9KBke+rs=
|
||||
github.com/fiatjaf/go-lnurl v1.8.3 h1:ONQUQsXIZKkzrzax2SMUr5W0PreluhO4tct1JM0V/MA=
|
||||
github.com/fiatjaf/go-lnurl v1.8.3/go.mod h1:0PPdV2GFnJK97ztksEIwrcEUVTothAKJsmzqPphAQhs=
|
||||
github.com/fiatjaf/go-lnurl v1.8.4 h1:uVH8833lVgvNqW3S0qr0I8VsIId5mVw0lE0KnEjgh/o=
|
||||
github.com/fiatjaf/go-lnurl v1.8.4/go.mod h1:0PPdV2GFnJK97ztksEIwrcEUVTothAKJsmzqPphAQhs=
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0 h1:HigjqNH+ApiO6gm7RV23jXNFuvwq+zgsWl4BJAfPWwE=
|
||||
github.com/fiatjaf/ln-decodepay v1.1.0/go.mod h1:2qdTT95b8Z4dfuxiZxXuJ1M7bQ9CrLieEA1DKC50q6s=
|
||||
github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw=
|
||||
github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g=
|
||||
github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4=
|
||||
github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20=
|
||||
github.com/frankban/quicktest v1.2.2/go.mod h1:Qh/WofXFeiAFII1aEBu529AtJo6Zg2VHscnEsbBnJ20=
|
||||
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
|
||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||
github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
|
||||
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
|
||||
github.com/go-errors/errors v1.0.1 h1:LUHzmkK3GUKUrL/1gfBUxAHzcev3apQlezX/+O7ma6w=
|
||||
github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q=
|
||||
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||
github.com/go-kit/kit v0.10.0/go.mod h1:xUsJbQ/Fp4kEt7AFgCuvyX4a71u8h9jB8tj/ORgOZ7o=
|
||||
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
|
||||
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
|
||||
github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
|
||||
github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas=
|
||||
github.com/go-openapi/errors v0.19.2/go.mod h1:qX0BLWsyaKfvhluLejVpVNwNRdXZhEbTA4kxxpKBC94=
|
||||
github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0=
|
||||
github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1:W3Z9FmVs9qj+KR4zFKmDPGiLdk1D9Rlm7cyMvf57TTg=
|
||||
github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc=
|
||||
github.com/go-openapi/strfmt v0.19.5/go.mod h1:eftuHTlB/dI8Uq8JJOyRlieZf+WkkxUuk0dgdHXr2Qk=
|
||||
github.com/go-openapi/swag v0.0.0-20160704191624-1d0bd113de87/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I=
|
||||
github.com/go-redis/redis/v8 v8.8.2 h1:O/NcHqobw7SEptA0yA6up6spZVFtwE06SXM8rgLtsP8=
|
||||
github.com/go-redis/redis/v8 v8.8.2/go.mod h1:F7resOH5Kdug49Otu24RjHWwgK7u9AmtqWMnCV1iP5Y=
|
||||
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
|
||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||
github.com/gogo/googleapis v1.1.0/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s=
|
||||
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
|
||||
github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
|
||||
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
|
||||
github.com/gogo/protobuf v1.2.2-0.20190723190241-65acae22fc9d/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E=
|
||||
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||
github.com/golang/mock v1.5.0 h1:jlYHihg//f7RRwuPfptm04yp4s7O6Kw8EZiVYIGcH0g=
|
||||
github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8=
|
||||
github.com/golang/protobuf v0.0.0-20161109072736-4bd1920723d7/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg=
|
||||
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
||||
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
||||
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
|
||||
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
|
||||
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
|
||||
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/golang/protobuf v1.4.3 h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM=
|
||||
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
||||
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||
github.com/google/go-cmp v0.2.1-0.20190312032427-6f77996f0c42/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/gofuzz v0.0.0-20161122191042-44d81051d367/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
|
||||
github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY=
|
||||
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
|
||||
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
|
||||
github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
|
||||
github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
|
||||
github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
|
||||
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
|
||||
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
|
||||
github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
|
||||
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
|
||||
github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
|
||||
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
|
||||
github.com/grpc-ecosystem/grpc-gateway v1.8.6/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
|
||||
github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
|
||||
github.com/hashicorp/consul/api v1.3.0/go.mod h1:MmDNSzIMUjNpY/mQ398R4bk2FnqQLoPndWW5VkKPlCE=
|
||||
github.com/hashicorp/consul/sdk v0.3.0/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8=
|
||||
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
|
||||
github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
|
||||
github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=
|
||||
github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
|
||||
github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU=
|
||||
github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU=
|
||||
github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4=
|
||||
github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
||||
github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
||||
github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
|
||||
github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90=
|
||||
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
|
||||
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
|
||||
github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=
|
||||
github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=
|
||||
github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I=
|
||||
github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc=
|
||||
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg=
|
||||
github.com/imroc/req v0.3.0 h1:3EioagmlSG+z+KySToa+Ylo3pTFZs+jh3Brl7ngU12U=
|
||||
github.com/imroc/req v0.3.0/go.mod h1:F+NZ+2EFSo6EFXdeIbpfE9hcC233id70kf0byW97Caw=
|
||||
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
|
||||
github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo=
|
||||
github.com/jackpal/gateway v1.0.5/go.mod h1:lTpwd4ACLXmpyiCTRtfiNyVnUmqT9RivzCDQetPfnjA=
|
||||
github.com/jackpal/go-nat-pmp v0.0.0-20170405195558-28a68d0c24ad/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc=
|
||||
github.com/jedib0t/go-pretty v4.3.0+incompatible/go.mod h1:XemHduiw8R651AF9Pt4FwCTKeG3oo7hrHJAoznj9nag=
|
||||
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=
|
||||
@@ -108,8 +269,18 @@ github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkr
|
||||
github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jinzhu/now v1.1.2 h1:eVKgfIdy9b6zbWBMgFpfDPoAMifwSZagU9HmEU6zgiI=
|
||||
github.com/jinzhu/now v1.1.2/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
|
||||
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
|
||||
github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4=
|
||||
github.com/jrick/logrotate v1.0.0 h1:lQ1bL/n9mBNeIXoTUoYRlK4dHuNJVofX9oWqBtPnSzI=
|
||||
github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ=
|
||||
github.com/json-iterator/go v0.0.0-20180612202835-f2b4162afba3/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
|
||||
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
|
||||
github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||
github.com/json-iterator/go v1.1.8/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
|
||||
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
|
||||
github.com/juju/clock v0.0.0-20190205081909-9c5c9712527c/go.mod h1:nD0vlnrUjcjJhqN5WuCWZyzfd5AHZAC9/ajvbSx69xA=
|
||||
github.com/juju/errors v0.0.0-20190806202954-0232dcc7464d/go.mod h1:W54LbzXuIE0boCoNJfwqpmkKJ1O4TCTZMetAt6jGk7Q=
|
||||
github.com/juju/loggo v0.0.0-20190526231331-6e530bcce5d8/go.mod h1:vgyd7OREkbtVEN/8IXZe5Ooef3LQePvuBm9UWj6ZL8U=
|
||||
@@ -118,12 +289,17 @@ github.com/juju/testing v0.0.0-20190723135506-ce30eb24acd2/go.mod h1:63prj8cnj0t
|
||||
github.com/juju/utils v0.0.0-20180820210520-bf9cc5bdd62d/go.mod h1:6/KLg8Wz/y2KVGWEpkK9vMNGkOnu4k/cqs8Z1fKjTOk=
|
||||
github.com/juju/version v0.0.0-20180108022336-b64dbd566305/go.mod h1:kE8gK5X0CImdr7qpSKl3xB2PmpySSmfj7zVbkZFs81U=
|
||||
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
|
||||
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
|
||||
github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4=
|
||||
github.com/kkdai/bstream v0.0.0-20181106074824-b3251f7901ec h1:n1NeQ3SgUHyISrjFFoO5dR748Is8dBL9qpaTNfphQrs=
|
||||
github.com/kkdai/bstream v0.0.0-20181106074824-b3251f7901ec/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
@@ -145,138 +321,446 @@ github.com/lightningnetwork/lnd/queue v1.0.3 h1:5ufYVE7lh9GJnL1wOoeO3bZ3aAHWNnkN
|
||||
github.com/lightningnetwork/lnd/queue v1.0.3/go.mod h1:YTkTVZCxz8tAYreH27EO3s8572ODumWrNdYW2E/YKxg=
|
||||
github.com/lightningnetwork/lnd/ticker v1.0.0 h1:S1b60TEGoTtCe2A0yeB+ecoj/kkS4qpwh6l+AkQEZwU=
|
||||
github.com/lightningnetwork/lnd/ticker v1.0.0/go.mod h1:iaLXJiVgI1sPANIF2qYYUJXjoksPNvGNYowB8aRbpX0=
|
||||
github.com/liyue201/goqr v0.0.0-20200803022322-df443203d4ea h1:uyJ13zfy6l79CM3HnVhDalIyZ4RJAyVfDrbnfFeJoC4=
|
||||
github.com/liyue201/goqr v0.0.0-20200803022322-df443203d4ea/go.mod h1:w4pGU9PkiX2hAWyF0yuHEHmYTQFAd6WHzp6+IY7JVjE=
|
||||
github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM=
|
||||
github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4=
|
||||
github.com/ltcsuite/ltcd v0.0.0-20190101042124-f37f8bf35796 h1:sjOGyegMIhvgfq5oaue6Td+hxZuf3tDC8lAPrFldqFw=
|
||||
github.com/ltcsuite/ltcd v0.0.0-20190101042124-f37f8bf35796/go.mod h1:3p7ZTf9V1sNPI5H8P3NkTFF4LuwMdPl2DodF60qAKqY=
|
||||
github.com/ltcsuite/ltcutil v0.0.0-20181217130922-17f3b04680b6/go.mod h1:8Vg/LTOO0KYa/vlHWJ6XZAevPQThGH5sufO0Hrou/lA=
|
||||
github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ=
|
||||
github.com/mailru/easyjson v0.0.0-20160728113105-d5b7844b561a/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
|
||||
github.com/makiuchi-d/gozxing v0.0.2 h1:TGSCQRXd9QL1ze1G1JE9sZBMEr6/HLx7m5ADlLUgq7E=
|
||||
github.com/makiuchi-d/gozxing v0.0.2/go.mod h1:Tt5nF+kNliU+5MDxqPpsFrtsWNdABQho/xdCZZVKCQc=
|
||||
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
|
||||
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
|
||||
github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
|
||||
github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
|
||||
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
|
||||
github.com/mattn/go-sqlite3 v1.14.5 h1:1IdxlwTNazvbKJQSxoJ5/9ECbEeaTTyeU7sEAZ5KKTQ=
|
||||
github.com/mattn/go-sqlite3 v1.14.5/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||
github.com/miekg/dns v0.0.0-20171125082028-79bfde677fa8 h1:PRMAcldsl4mXKJeRNB/KVNz6TlbS6hk2Rs42PqgU3Ws=
|
||||
github.com/miekg/dns v0.0.0-20171125082028-79bfde677fa8/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
|
||||
github.com/miekg/dns v1.0.14 h1:9jZdLNd/P4+SfEJ0TNyxYpsK8N4GtfylBLqtbYN1sbA=
|
||||
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
|
||||
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
|
||||
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
|
||||
github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI=
|
||||
github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg=
|
||||
github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY=
|
||||
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
|
||||
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v0.0.0-20180320133207-05fbef0ca5da/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||
github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
||||
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
||||
github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw=
|
||||
github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg=
|
||||
github.com/nats-io/jwt v0.3.2/go.mod h1:/euKqTS1ZD+zzjYrY7pseZrTtWQSjujC7xjPc8wL6eU=
|
||||
github.com/nats-io/nats-server/v2 v2.1.2/go.mod h1:Afk+wRZqkMQs/p45uXdrVLuab3gwv3Z8C4HTBu8GD/k=
|
||||
github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w=
|
||||
github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
|
||||
github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
github.com/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=
|
||||
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
|
||||
github.com/oklog/oklog v0.3.2/go.mod h1:FCV+B7mhrz4o+ueLpx+KqkyXRGMWOYEvfiXtdGtbWGs=
|
||||
github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA=
|
||||
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
|
||||
github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo=
|
||||
github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs=
|
||||
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
|
||||
github.com/onsi/ginkgo v1.15.0 h1:1V1NfVQR87RtWAgp1lv9JZJ5Jap+XFGKPi00andXGi4=
|
||||
github.com/onsi/ginkgo v1.15.0/go.mod h1:hF8qUzuuC8DJGygJH3726JnCZX4MYbRB8yFfISqnKUg=
|
||||
github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA=
|
||||
github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA=
|
||||
github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU=
|
||||
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
||||
github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
||||
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
|
||||
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
|
||||
github.com/onsi/gomega v1.10.5 h1:7n6FEkpFmfCoo2t+YYqXH0evK+a9ICQz0xcAy9dYcaQ=
|
||||
github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48=
|
||||
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk=
|
||||
github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492/go.mod h1:Ngi6UdF0k5OKD5t5wlmGhe/EDKPoUM3BXZSSfIuJbis=
|
||||
github.com/opentracing/basictracer-go v1.0.0/go.mod h1:QfBfYuafItcjQuMwinw9GhYKwFXS9KnPs5lxoYwgW74=
|
||||
github.com/opentracing/opentracing-go v1.0.2/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
|
||||
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
|
||||
github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxSfWAKL3wpBW7V8scJMt8N8gnaMCS9E/cA=
|
||||
github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw=
|
||||
github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4=
|
||||
github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4=
|
||||
github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HDbW65HOY=
|
||||
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
|
||||
github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM=
|
||||
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
|
||||
github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k=
|
||||
github.com/pegasus-kv/thrift v0.13.0 h1:4ESwaNoHImfbHa9RUGJiJZ4hrxorihZHk5aarYwY8d4=
|
||||
github.com/pegasus-kv/thrift v0.13.0/go.mod h1:Gl9NT/WHG6ABm6NsrbfE8LiJN0sAyneCrvB4qN4NPqQ=
|
||||
github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac=
|
||||
github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc=
|
||||
github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY=
|
||||
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA=
|
||||
github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
|
||||
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
|
||||
github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs=
|
||||
github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
|
||||
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
|
||||
github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og=
|
||||
github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M=
|
||||
github.com/prometheus/client_golang v1.10.0/go.mod h1:WJM3cc3yu7XKBKa/I8WeZm+V3eltZnBwfENSU7mdogU=
|
||||
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
||||
github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
||||
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/prometheus/client_model v0.1.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
|
||||
github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
|
||||
github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
|
||||
github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
|
||||
github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA=
|
||||
github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo=
|
||||
github.com/prometheus/common v0.18.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16Clt/msog/s=
|
||||
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
||||
github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
||||
github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
|
||||
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
|
||||
github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A=
|
||||
github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
|
||||
github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
|
||||
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
|
||||
github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
|
||||
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
|
||||
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
|
||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
|
||||
github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E=
|
||||
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
|
||||
github.com/sethvargo/go-limiter v0.7.2 h1:FgC4N7RMpV5gMrUdda15FaFTkQ/L4fEqM7seXMs4oO8=
|
||||
github.com/sethvargo/go-limiter v0.7.2/go.mod h1:C0kbSFbiriE5k2FFOe18M1YZbAR2Fiwf72uGu0CXCcU=
|
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
|
||||
github.com/sirupsen/logrus v1.2.0 h1:juTguoYk5qI21pwyTXY3B3Y5cOTH3ZUyZCg1v/mihuo=
|
||||
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
||||
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
||||
github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
|
||||
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
|
||||
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
|
||||
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
|
||||
github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s=
|
||||
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
|
||||
github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
|
||||
github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY=
|
||||
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72 h1:qLC7fQah7D6K1B0ujays3HV9gkFtllcxhzImRR7ArPQ=
|
||||
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
|
||||
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
|
||||
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
||||
github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
|
||||
github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
||||
github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=
|
||||
github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=
|
||||
github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
|
||||
github.com/stretchr/testify v0.0.0-20151208002404-e3a8ff8ce365/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/tidwall/assert v0.1.0 h1:aWcKyRBUAdLoVebxo95N7+YZVTFF/ASTr7BN4sLP6XI=
|
||||
github.com/tidwall/assert v0.1.0/go.mod h1:QLYtGyeqse53vuELQheYl9dngGCJQ+mTtlxcktb+Kj8=
|
||||
github.com/tidwall/btree v0.6.1 h1:75VVgBeviiDO+3g4U+7+BaNBNhNINxB0ULPT3fs9pMY=
|
||||
github.com/tidwall/btree v0.6.1/go.mod h1:TzIRzen6yHbibdSfK6t8QimqbUnoxUSrZfeW7Uob0q4=
|
||||
github.com/tidwall/buntdb v1.2.7 h1:SIyObKAymzLyGhDeIhVk2Yc1/EwfCC75Uyu77CHlVoA=
|
||||
github.com/tidwall/buntdb v1.2.7/go.mod h1:b6KvZM27x/8JLI5hgRhRu60pa3q0Tz9c50TyD46OHUM=
|
||||
github.com/tidwall/gjson v1.6.0/go.mod h1:P256ACg0Mn+j1RXIDXoss50DeIABTYK1PULOJHhxOls=
|
||||
github.com/tidwall/gjson v1.6.1 h1:LRbvNuNuvAiISWg6gxLEFuCe72UKy5hDqhxW/8183ws=
|
||||
github.com/tidwall/gjson v1.6.1/go.mod h1:BaHyNc5bjzYkPqgLq7mdVzeiRtULKULXLgZFKsxEHI0=
|
||||
github.com/tidwall/gjson v1.10.2 h1:APbLGOM0rrEkd8WBw9C24nllro4ajFuJu0Sc9hRz8Bo=
|
||||
github.com/tidwall/gjson v1.10.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/grect v0.1.3 h1:z9YwQAMUxVSBde3b7Sl8Da37rffgNfZ6Fq6h9t6KdXE=
|
||||
github.com/tidwall/grect v0.1.3/go.mod h1:8GMjwh3gPZVpLBI/jDz9uslCe0dpxRpWDdtN0lWAS/E=
|
||||
github.com/tidwall/lotsa v1.0.2 h1:dNVBH5MErdaQ/xd9s769R31/n2dXavsQ0Yf4TMEHHw8=
|
||||
github.com/tidwall/lotsa v1.0.2/go.mod h1:X6NiU+4yHA3fE3Puvpnn1XMDrFZrE9JO2/w+UMuqgR8=
|
||||
github.com/tidwall/match v1.0.1 h1:PnKP62LPNxHKTwvHHZZzdOAOCtsJTjo6dZLCwpKm5xc=
|
||||
github.com/tidwall/match v1.0.1/go.mod h1:LujAq0jyVjBy028G1WhWfIzbpQfMO8bBZ6Tyb0+pL9E=
|
||||
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
||||
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
|
||||
github.com/tidwall/pretty v1.0.2 h1:Z7S3cePv9Jwm1KwS0513MRaoUe3S01WPbLNV40pwWZU=
|
||||
github.com/tidwall/pretty v1.0.2/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
|
||||
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
|
||||
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/tidwall/rtred v0.1.2 h1:exmoQtOLvDoO8ud++6LwVsAMTu0KPzLTUrMln8u1yu8=
|
||||
github.com/tidwall/rtred v0.1.2/go.mod h1:hd69WNXQ5RP9vHd7dqekAz+RIdtfBogmglkZSRxCHFQ=
|
||||
github.com/tidwall/tinyqueue v0.1.1 h1:SpNEvEggbpyN5DIReaJ2/1ndroY8iyEGxPYxoSaymYE=
|
||||
github.com/tidwall/tinyqueue v0.1.1/go.mod h1:O/QNHwrnjqr6IHItYrzoHAKYhBkLI67Q096fQP5zMYw=
|
||||
github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
|
||||
github.com/tv42/zbase32 v0.0.0-20160707012821-501572607d02/go.mod h1:tHlrkM198S068ZqfrO6S8HsoJq2bF3ETfTL+kt4tInY=
|
||||
github.com/urfave/cli v1.18.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
|
||||
github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
|
||||
github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
|
||||
github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=
|
||||
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
|
||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
go.etcd.io/bbolt v1.3.3 h1:MUGmc65QhB3pIlaQ5bB4LwqSj6GIonVJXpZiaKNyaKk=
|
||||
go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
|
||||
go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg=
|
||||
go.mongodb.org/mongo-driver v1.0.3/go.mod h1:u7ryQJ+DOzQmeO7zB6MHyr8jkEQvC8vH7qLUO4lqsUM=
|
||||
go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk=
|
||||
go.opencensus.io v0.20.2/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk=
|
||||
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
||||
go.opentelemetry.io/otel v0.19.0 h1:Lenfy7QHRXPZVsw/12CWpxX6d/JkrX8wrx2vO8G80Ng=
|
||||
go.opentelemetry.io/otel v0.19.0/go.mod h1:j9bF567N9EfomkSidSfmMwIwIBuP37AMAIzVW85OxSg=
|
||||
go.opentelemetry.io/otel/metric v0.19.0 h1:dtZ1Ju44gkJkYvo+3qGqVXmf88tc+a42edOywypengg=
|
||||
go.opentelemetry.io/otel/metric v0.19.0/go.mod h1:8f9fglJPRnXuskQmKpnad31lcLJ2VmNNqIsx/uIwBSc=
|
||||
go.opentelemetry.io/otel/oteltest v0.19.0 h1:YVfA0ByROYqTwOxqHVZYZExzEpfZor+MU1rU+ip2v9Q=
|
||||
go.opentelemetry.io/otel/oteltest v0.19.0/go.mod h1:tI4yxwh8U21v7JD6R3BcA/2+RBoTKFexE/PJ/nSO7IA=
|
||||
go.opentelemetry.io/otel/trace v0.19.0 h1:1ucYlenXIDA1OlHVLDZKX0ObXV5RLaq06DtUKz5e5zc=
|
||||
go.opentelemetry.io/otel/trace v0.19.0/go.mod h1:4IXiNextNOpPnRlI4ryK69mn5iC84bjBWZQA5DXz/qg=
|
||||
go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
|
||||
go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
|
||||
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
|
||||
go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4=
|
||||
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA=
|
||||
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
|
||||
go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM=
|
||||
golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190211182817-74369b46fc67/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 h1:cg5LA/zNPRzIXIWSCxQW10Rvpy94aQh3LT/ShoCpkHw=
|
||||
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
|
||||
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
|
||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/net v0.0.0-20170114055629-f2499483f923/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20181106065722-10aee1819953/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190206173232-65e2d4e15006/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
|
||||
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20191004110552-13f9640d40b9/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20191105084925-a882066a44e0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||
golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
|
||||
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb h1:eBmm0M9fYhWpKZLjQUUKka/LtIxf46G4fxeEz5KJr9U=
|
||||
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a h1:DcqTD9SDLc+1P/r1EmRBwnVsrOwW+kk2vWf9n+1sGhs=
|
||||
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20170830134202-bb24a47a89ea/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190209173611-3b5209105503/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210309074719-68d13333faf2 h1:46ULzRKLh1CwgRq2dC5SlBzEqqNCi8rreOZnNrbqcIY=
|
||||
golang.org/x/sys v0.0.0-20210309074719-68d13333faf2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2 h1:z99zHgr7hKfrUcX/KsoJk5FJfjTceCKIp96+biqP4To=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ=
|
||||
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2 h1:+DCIGbF/swA92ohVg0//6X2IVY3KZs6p9mix0ziNYJM=
|
||||
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0 h1:/5xXl8Y5W96D+TtHSlonuFqGHIWVuyCkGJLwGh9JJFs=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20181011042414-1f849cf54d09/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
|
||||
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
||||
golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
|
||||
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||
google.golang.org/genproto v0.0.0-20190201180003-4b09977fb922/go.mod h1:L3J43x8/uS+qIUoksaLKe6OS3nUKxOKuIFz1sl2/jx4=
|
||||
google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
|
||||
google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
|
||||
google.golang.org/genproto v0.0.0-20190530194941-fb225487d101/go.mod h1:z3L6/3dTEVtUr6QSP8miRzeRqwQOioJ9I66odjN4I7s=
|
||||
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
|
||||
google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio=
|
||||
google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs=
|
||||
google.golang.org/grpc v1.18.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM=
|
||||
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
|
||||
google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
|
||||
google.golang.org/grpc v1.22.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
|
||||
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
|
||||
google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
|
||||
google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
|
||||
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
|
||||
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
||||
google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM=
|
||||
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw=
|
||||
gopkg.in/errgo.v1 v1.0.1/go.mod h1:3NjfXwocQRYAPTq4/fzX+CwUhPRcR/azYRhj8G+LqMo=
|
||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o=
|
||||
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.3.5 h1:TdMJTlG8kvepsvZdy/gPeYEBdwKdwFFjH1AQTua9BOU=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.3.5/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.1 h1:bUOFHtHhuhPekjHGe1Q1BmITvtBLdQI4yjSMC405KcU=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.1/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201070229-f317e8453e9f h1:BnYlAEmRJi8YEcSbXO6PlAVwl7WpKJvMqkijHZmO8Gw=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201070229-f317e8453e9f/go.mod h1:lUH49SRidDcQGyXPIL9tR2cN3vztcLBo47AqFUgHgIA=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201074627-babf9f2cc955 h1:uhQUyDqilPUh58BWtIeSAupjovs1QQjC6pEoErqD86o=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211201074627-babf9f2cc955/go.mod h1:lUH49SRidDcQGyXPIL9tR2cN3vztcLBo47AqFUgHgIA=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211207185736-224e4f70c5ad h1:HR3vqf1DS7hEQ0j77J4ctumZgzDIHNXZtag60U9OOig=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211207185736-224e4f70c5ad/go.mod h1:lUH49SRidDcQGyXPIL9tR2cN3vztcLBo47AqFUgHgIA=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211217193303-c005cce171ac h1:EcXyrTUaQJYiHtLQstXdW04sRH9HwH9mpaxy9Lkcomc=
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211217193303-c005cce171ac/go.mod h1:lUH49SRidDcQGyXPIL9tR2cN3vztcLBo47AqFUgHgIA=
|
||||
gopkg.in/macaroon-bakery.v2 v2.0.1/go.mod h1:B4/T17l+ZWGwxFSZQmlBwp25x+og7OkhETfr3S9MbIA=
|
||||
gopkg.in/macaroon.v2 v2.0.0/go.mod h1:+I6LnTMkm/uV5ew/0nsulNjL16SK4+C8yDmRUzHR17I=
|
||||
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=
|
||||
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/tucnak/telebot.v2 v2.3.5 h1:TdMJTlG8kvepsvZdy/gPeYEBdwKdwFFjH1AQTua9BOU=
|
||||
gopkg.in/tucnak/telebot.v2 v2.3.5/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
|
||||
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 h1:yiW+nvdHb9LVqSHQBXfZCieqV4fzYhNBql77zY0ykqs=
|
||||
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637/go.mod h1:BHsqpu/nsuzkT5BpiH1EMZPLyqSMM8JbIavyFACoFNk=
|
||||
gopkg.in/tucnak/telebot.v2 v2.4.1 h1:bUOFHtHhuhPekjHGe1Q1BmITvtBLdQI4yjSMC405KcU=
|
||||
gopkg.in/tucnak/telebot.v2 v2.4.1/go.mod h1:BgaIIx50PSRS9pG59JH+geT82cfvoJU/IaI5TJdN3v8=
|
||||
gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI=
|
||||
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
|
||||
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/sqlite v1.1.4 h1:PDzwYE+sI6De2+mxAneV9Xs11+ZyKV6oxD3wDGkaNvM=
|
||||
gorm.io/driver/sqlite v1.1.4/go.mod h1:mJCeTFr7+crvS+TRnWc5Z3UvwxUN1BGBLMrf5LA9DYw=
|
||||
gorm.io/gorm v1.20.7/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
|
||||
@@ -284,3 +768,14 @@ gorm.io/gorm v1.21.12 h1:3fQM0Eiz7jcJEhPggHEpoYnsGZqynMzverL77DV40RM=
|
||||
gorm.io/gorm v1.21.12/go.mod h1:F+OptMscr0P2F2qU97WT1WimdH9GaQPoDW7AYd5i2Y0=
|
||||
honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
|
||||
k8s.io/apimachinery v0.0.0-20191123233150-4c4803ed55e3 h1:FErmbNIJruD5GT2oVEjtPn5Ar5+rcWJsC8/PPUkR0s4=
|
||||
k8s.io/apimachinery v0.0.0-20191123233150-4c4803ed55e3/go.mod h1:b9qmWdKlLuU9EBh+06BtLcSf/Mu89rWL33naRxs1uZg=
|
||||
k8s.io/gengo v0.0.0-20190128074634-0689ccc1d7d6/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0=
|
||||
k8s.io/klog v0.0.0-20181102134211-b9b56d5dfc92/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk=
|
||||
k8s.io/klog v1.0.0/go.mod h1:4Bi6QPql/J/LkTDqv7R/cd3hPo4k2DG6Ptcz060Ez5I=
|
||||
k8s.io/kube-openapi v0.0.0-20191107075043-30be4d16710a/go.mod h1:1TqjTSzOxsLGIKfj0lK8EeCP7K1iUG65v09OM0/WG5E=
|
||||
sigs.k8s.io/structured-merge-diff v0.0.0-20190525122527-15d366b2352e/go.mod h1:wWxsB5ozmmv/SG7nM11ayaAW51xMvak/t1r0CSlcokI=
|
||||
sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o=
|
||||
sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU=
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
helpMessage = "ℹ️ *Info*\n_This bot is a Bitcoin Lightning ⚡️ wallet that can sends tips on Telegram. To tip, add the bot to a group chat. The basic unit of tips are Satoshis (sat). 100,000,000 sat = 1 Bitcoin. There will only ever be 21 Million Bitcoin. Type /info for more._\n\n" +
|
||||
"❤️ *Donate*\n" +
|
||||
"_This bot charges no fees but costs satoshis to operate. If you like the bot, please consider supporting this project with a donation. To donate, use_ `/donate 1000`\n\n" +
|
||||
"⚙️ *Commands*\n" +
|
||||
"*/tip* 🏅 Reply to a message to tip: `/tip <amount> [<memo>]`\n" +
|
||||
"*/balance* 👑 Check balance: `/balance`\n" +
|
||||
"*/send* 💸 Send funds to a Telegram user: `/send <amount> <@user> [<memo>]`\n" +
|
||||
"*/invoice* ⚡️ Receive over Lightning: `/invoice <amount> [<memo>]`\n" +
|
||||
"*/pay* ⚡️ Pay over Lightning: `/pay <invoice>`\n" +
|
||||
"*/donate* ❤️ Donate to the project: `/donate 1000`\n" +
|
||||
"*/advanced* 🤖 Read the advanced help.\n" +
|
||||
"*/help* 📖 Read this help."
|
||||
|
||||
infoMessage = "🧡 *Bitcoin*\n" +
|
||||
"_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._\n\n" +
|
||||
"🧮 *Economnics*\n" +
|
||||
"_The smallest unit of Bitcoin are Satoshis (sat) and 100,000,000 sat = 1 Bitcoin. There will only ever be 21 Million Bitcoin. The fiat currency value of Bitcoin can change daily. However, if you live on a Bitcoin standard 1 sat will always equal 1 sat._\n\n" +
|
||||
"⚡️ *The Lightning Network*\n" +
|
||||
"_The Lightning Network is a payment protocol that enables fast and cheap Bitcoin payments that require almost no energy. It is what scales Bitcoin to the billions of people around the world._\n\n" +
|
||||
"📲 *Lightning Wallets*\n" +
|
||||
"_Your funds on this bot can be sent to any other Lightning wallet and vice versa. Recommended Lightning wallets for your phone are_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (non-custodial), or_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(easy)_.\n\n" +
|
||||
"📄 *Open Source*\n" +
|
||||
"_This bot is free and_ [open source](https://github.com/LightningTipBot/LightningTipBot) _software. You can run it on your own computer and use it in your own community._\n\n" +
|
||||
"✈️ *Telegram*\n" +
|
||||
"_Add this bot to your Telegram group chat to /tip posts. If you make the bot admin of the group it will also clean up commands to keep the chat tidy._\n\n" +
|
||||
// "🏛 *Terms*\n" +
|
||||
// "_We are not custodian of your funds. Any amount you load onto your wallet will be legally considered a donation that belongs to us. We will act in your best interest but we're also aware that the situation without KYC is tricky until we figure something out. Do not give us all your money. Be aware that this bot is in beta development. Use at your own risk._\n\n" +
|
||||
"❤️ *Donate*\n" +
|
||||
"_This bot charges no fees but costs satoshis to operate. If you like the bot, please consider supporting this project with a donation. To donate, To donate, use_ `/donate 1000`"
|
||||
|
||||
advancedMessage = "🤖 *Advanced commands*\n\n" +
|
||||
"*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)\n"
|
||||
)
|
||||
|
||||
func (bot TipBot) helpHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
if !m.Private() {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
}
|
||||
bot.telegram.Send(m.Sender, helpMessage, tb.NoPreview)
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) infoHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
if !m.Private() {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
}
|
||||
bot.telegram.Send(m.Sender, infoMessage, tb.NoPreview)
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) advancedHelpHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
if !m.Private() {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
}
|
||||
bot.telegram.Send(m.Sender, advancedMessage, tb.NoPreview)
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
bot *telegram.TipBot
|
||||
}
|
||||
|
||||
func New(b *telegram.TipBot) Service {
|
||||
return Service{
|
||||
bot: b,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func (s Service) UnbanUser(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := s.getUserByTelegramId(r)
|
||||
if err != nil {
|
||||
log.Errorf("[ADMIN] could not ban user: %v", err)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !user.Banned && !strings.HasPrefix(user.Wallet.Adminkey, "banned_") {
|
||||
log.Infof("[ADMIN] user is not banned. Aborting.")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
user.Banned = false
|
||||
adminSlice := strings.Split(user.Wallet.Adminkey, "_")
|
||||
user.Wallet.Adminkey = adminSlice[len(adminSlice)-1]
|
||||
err = telegram.UpdateUserRecord(user, *s.bot)
|
||||
if err != nil {
|
||||
log.Errorf("[ADMIN] could not update user: %v", err)
|
||||
return
|
||||
}
|
||||
log.Infof("[ADMIN] Unbanned user (%s)", user.ID)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func (s Service) BanUser(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := s.getUserByTelegramId(r)
|
||||
if err != nil {
|
||||
log.Errorf("[ADMIN] could not ban user: %v", err)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if user.Banned {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
log.Infof("[ADMIN] user is already banned. Aborting.")
|
||||
return
|
||||
}
|
||||
user.Banned = true
|
||||
if reason := r.URL.Query().Get("reason"); reason != "" {
|
||||
user.Wallet.Adminkey = fmt.Sprintf("%s_%s", reason, user.Wallet.Adminkey)
|
||||
}
|
||||
user.Wallet.Adminkey = fmt.Sprintf("%s_%s", "banned", user.Wallet.Adminkey)
|
||||
err = telegram.UpdateUserRecord(user, *s.bot)
|
||||
if err != nil {
|
||||
log.Errorf("[ADMIN] could not update user: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("[ADMIN] Banned user (%s)", user.ID)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func (s Service) getUserByTelegramId(r *http.Request) (*lnbits.User, error) {
|
||||
user := &lnbits.User{}
|
||||
v := mux.Vars(r)
|
||||
if v["id"] == "" {
|
||||
return nil, fmt.Errorf("invalid id")
|
||||
}
|
||||
tx := s.bot.Database.Where("telegram_id = ? COLLATE NOCASE", v["id"]).First(user)
|
||||
if tx.Error != nil {
|
||||
return nil, tx.Error
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func LoggingMiddleware(prefix string, next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
log.Tracef("[%s] %s %s", prefix, r.Method, r.URL.Path)
|
||||
log.Tracef("[%s]\n%s", prefix, dump(r))
|
||||
r.BasicAuth()
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func dump(r *http.Request) string {
|
||||
x, err := httputil.DumpRequest(r, true)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(x)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Proxy(wr http.ResponseWriter, req *http.Request, rawUrl string) error {
|
||||
|
||||
client := &http.Client{Timeout: time.Second * 10}
|
||||
|
||||
//http: Request.RequestURI can't be set in client requests.
|
||||
//http://golang.org/src/pkg/net/http/client.go
|
||||
req.RequestURI = ""
|
||||
|
||||
u, err := url.Parse(rawUrl)
|
||||
if err != nil {
|
||||
http.Error(wr, "Server Error", http.StatusInternalServerError)
|
||||
log.Println("ServeHTTP:", err)
|
||||
return err
|
||||
}
|
||||
req.URL.Host = u.Host
|
||||
req.URL.Scheme = u.Scheme
|
||||
req.Host = req.URL.Host
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
http.Error(wr, "Server Error", http.StatusInternalServerError)
|
||||
log.Println("ServeHTTP:", err)
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
log.Tracef("[Proxy] Proxy request status: %s", resp.Status)
|
||||
if resp.StatusCode > 300 {
|
||||
return fmt.Errorf("invalid response")
|
||||
}
|
||||
delHopHeaders(resp.Header)
|
||||
copyHeader(wr.Header(), resp.Header)
|
||||
wr.WriteHeader(resp.StatusCode)
|
||||
_, err = io.Copy(wr, resp.Body)
|
||||
return err
|
||||
}
|
||||
|
||||
// Hop-by-hop headers. These are removed when sent to the backend.
|
||||
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
|
||||
var hopHeaders = []string{
|
||||
"Connection",
|
||||
"Keep-Alive",
|
||||
"Proxy-Authenticate",
|
||||
"Proxy-Authorization",
|
||||
"Te", // canonicalized version of "TE"
|
||||
"Trailers",
|
||||
"Transfer-Encoding",
|
||||
"Upgrade",
|
||||
}
|
||||
|
||||
func copyHeader(dst, src http.Header) {
|
||||
for k, vv := range src {
|
||||
for _, v := range vv {
|
||||
dst.Add(k, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func delHopHeaders(header http.Header) {
|
||||
for _, h := range hopHeaders {
|
||||
header.Del(h)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
httpServer *http.Server
|
||||
router *mux.Router
|
||||
}
|
||||
|
||||
const (
|
||||
StatusError = "ERROR"
|
||||
StatusOk = "OK"
|
||||
)
|
||||
|
||||
func NewServer(address string) *Server {
|
||||
srv := &http.Server{
|
||||
Addr: address,
|
||||
// Good practice: enforce timeouts for servers you create!
|
||||
WriteTimeout: 15 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
}
|
||||
apiServer := &Server{
|
||||
httpServer: srv,
|
||||
}
|
||||
apiServer.router = mux.NewRouter()
|
||||
apiServer.httpServer.Handler = apiServer.router
|
||||
go apiServer.httpServer.ListenAndServe()
|
||||
log.Infof("[LNURL] Server started at %s", internal.Configuration.Bot.LNURLServerUrl.Host)
|
||||
return apiServer
|
||||
}
|
||||
|
||||
func (w *Server) ListenAndServe() {
|
||||
go w.httpServer.ListenAndServe()
|
||||
}
|
||||
func (w *Server) PathPrefix(path string, handler http.Handler) {
|
||||
w.router.PathPrefix(path).Handler(handler)
|
||||
}
|
||||
func (w *Server) AppendRoute(path string, handler func(http.ResponseWriter, *http.Request), methods ...string) {
|
||||
r := w.router.HandleFunc(path, LoggingMiddleware("API", handler))
|
||||
if len(methods) > 0 {
|
||||
r.Methods(methods...)
|
||||
}
|
||||
}
|
||||
|
||||
func NotFoundHandler(writer http.ResponseWriter, err error) {
|
||||
log.Errorln(err)
|
||||
// return 404 on any error
|
||||
http.Error(writer, "404 page not found", http.StatusNotFound)
|
||||
}
|
||||
|
||||
func WriteResponse(writer http.ResponseWriter, response interface{}) error {
|
||||
jsonResponse, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = writer.Write(jsonResponse)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/jinzhu/configor"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var Configuration = struct {
|
||||
Bot BotConfiguration `yaml:"bot"`
|
||||
Telegram TelegramConfiguration `yaml:"telegram"`
|
||||
Database DatabaseConfiguration `yaml:"database"`
|
||||
Lnbits LnbitsConfiguration `yaml:"lnbits"`
|
||||
}{}
|
||||
|
||||
type BotConfiguration struct {
|
||||
HttpProxy string `yaml:"http_proxy"`
|
||||
LNURLServer string `yaml:"lnurl_server"`
|
||||
LNURLServerUrl *url.URL `yaml:"-"`
|
||||
LNURLHostName string `yaml:"lnurl_public_host_name"`
|
||||
LNURLHostUrl *url.URL `yaml:"-"`
|
||||
LNURLSendImage bool `yaml:"lnurl_image"`
|
||||
}
|
||||
|
||||
type TelegramConfiguration struct {
|
||||
MessageDisposeDuration int64 `yaml:"message_dispose_duration"`
|
||||
ApiKey string `yaml:"api_key"`
|
||||
}
|
||||
type DatabaseConfiguration struct {
|
||||
DbPath string `yaml:"db_path"`
|
||||
ShopBuntDbPath string `yaml:"shop_buntdb_path"`
|
||||
BuntDbPath string `yaml:"buntdb_path"`
|
||||
TransactionsPath string `yaml:"transactions_path"`
|
||||
}
|
||||
|
||||
type LnbitsConfiguration struct {
|
||||
AdminId string `yaml:"admin_id"`
|
||||
AdminKey string `yaml:"admin_key"`
|
||||
Url string `yaml:"url"`
|
||||
LnbitsPublicUrl string `yaml:"lnbits_public_url"`
|
||||
WebhookServer string `yaml:"webhook_server"`
|
||||
WebhookServerUrl *url.URL `yaml:"-"`
|
||||
}
|
||||
|
||||
func init() {
|
||||
err := configor.Load(&Configuration, "config.yaml")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
webhookUrl, err := url.Parse(Configuration.Lnbits.WebhookServer)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
Configuration.Lnbits.WebhookServerUrl = webhookUrl
|
||||
|
||||
lnUrl, err := url.Parse(Configuration.Bot.LNURLServer)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
Configuration.Bot.LNURLServerUrl = lnUrl
|
||||
hostname, err := url.Parse(Configuration.Bot.LNURLHostName)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
Configuration.Bot.LNURLHostUrl = hostname
|
||||
checkLnbitsConfiguration()
|
||||
}
|
||||
|
||||
func checkLnbitsConfiguration() {
|
||||
if Configuration.Lnbits.Url == "" {
|
||||
panic(fmt.Errorf("please configure a lnbits url"))
|
||||
}
|
||||
if Configuration.Lnbits.LnbitsPublicUrl == "" {
|
||||
log.Warnf("Please specify a lnbits public url otherwise users won't be able to")
|
||||
} else {
|
||||
if !strings.HasSuffix(Configuration.Lnbits.LnbitsPublicUrl, "/") {
|
||||
Configuration.Lnbits.LnbitsPublicUrl = Configuration.Lnbits.LnbitsPublicUrl + "/"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func MigrateAnonIdInt32Hash(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))
|
||||
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)
|
||||
log.Errorln(errmsg)
|
||||
return tx.Error
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package errors
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
type TipBotError struct {
|
||||
Message string `json:"message"`
|
||||
Err error
|
||||
Code TipBotErrorType `json:"code"`
|
||||
}
|
||||
|
||||
func (e TipBotError) Error() string {
|
||||
j, err := json.Marshal(&e)
|
||||
if err != nil {
|
||||
return e.Message
|
||||
}
|
||||
return string(j)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package errors
|
||||
|
||||
import "fmt"
|
||||
|
||||
type TipBotErrorType int
|
||||
|
||||
const (
|
||||
UnknownError TipBotErrorType = iota
|
||||
NoReplyMessageError
|
||||
InvalidSyntaxError
|
||||
MaxReachedError
|
||||
NoPhotoError
|
||||
NoFileFoundError
|
||||
NotActiveError
|
||||
InvalidTypeError
|
||||
)
|
||||
|
||||
const (
|
||||
UserNoWalletError TipBotErrorType = 2000 + iota
|
||||
BalanceToLowError
|
||||
SelfPaymentError
|
||||
NoPrivateChatError
|
||||
GetBalanceError
|
||||
DecodeAmountError
|
||||
DecodePerUserAmountError
|
||||
InvalidAmountError
|
||||
InvalidAmountPerUserError
|
||||
)
|
||||
|
||||
const (
|
||||
NoShopError TipBotErrorType = 3000 + iota
|
||||
NotShopOwnerError
|
||||
ShopNoOwnerError
|
||||
ItemIdMismatchError
|
||||
)
|
||||
|
||||
var errMap = map[TipBotErrorType]TipBotError{
|
||||
UserNoWalletError: userNoWallet,
|
||||
NoReplyMessageError: noReplyMessage,
|
||||
InvalidSyntaxError: invalidSyntax,
|
||||
InvalidAmountPerUserError: invalidAmount,
|
||||
InvalidAmountError: invalidAmountPerUser,
|
||||
NoPrivateChatError: noPrivateChat,
|
||||
ShopNoOwnerError: shopNoOwner,
|
||||
NotShopOwnerError: notShopOwner,
|
||||
MaxReachedError: maxReached,
|
||||
NoShopError: noShop,
|
||||
SelfPaymentError: selfPayment,
|
||||
NoPhotoError: noPhoto,
|
||||
ItemIdMismatchError: itemIdMismatch,
|
||||
NoFileFoundError: noFileFound,
|
||||
UnknownError: unknown,
|
||||
NotActiveError: notActive,
|
||||
InvalidTypeError: invalidType,
|
||||
}
|
||||
|
||||
var (
|
||||
userNoWallet = TipBotError{Err: fmt.Errorf("user has no wallet")}
|
||||
noReplyMessage = TipBotError{Err: fmt.Errorf("no reply message")}
|
||||
invalidSyntax = TipBotError{Err: fmt.Errorf("invalid syntax")}
|
||||
invalidAmount = TipBotError{Err: fmt.Errorf("invalid amount")}
|
||||
invalidAmountPerUser = TipBotError{Err: fmt.Errorf("invalid amount per user")}
|
||||
noPrivateChat = TipBotError{Err: fmt.Errorf("no private chat")}
|
||||
shopNoOwner = TipBotError{Err: fmt.Errorf("shop has no owner")}
|
||||
notShopOwner = TipBotError{Err: fmt.Errorf("user is not shop owner")}
|
||||
maxReached = TipBotError{Err: fmt.Errorf("maximum reached")}
|
||||
noShop = TipBotError{Err: fmt.Errorf("user has no shop")}
|
||||
selfPayment = TipBotError{Err: fmt.Errorf("can't pay yourself")}
|
||||
noPhoto = TipBotError{Err: fmt.Errorf("no photo in message")}
|
||||
itemIdMismatch = TipBotError{Err: fmt.Errorf("item id mismatch")}
|
||||
noFileFound = TipBotError{Err: fmt.Errorf("no file found")}
|
||||
unknown = TipBotError{Err: fmt.Errorf("unknown error")}
|
||||
notActive = TipBotError{Err: fmt.Errorf("element not active")}
|
||||
invalidType = TipBotError{Err: fmt.Errorf("invalid type")}
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
package i18n
|
||||
|
||||
import (
|
||||
"github.com/BurntSushi/toml"
|
||||
"github.com/nicksnyder/go-i18n/v2/i18n"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"golang.org/x/text/language"
|
||||
)
|
||||
|
||||
var Bundle *i18n.Bundle
|
||||
|
||||
func init() {
|
||||
Bundle = RegisterLanguages()
|
||||
}
|
||||
|
||||
func RegisterLanguages() *i18n.Bundle {
|
||||
bundle := i18n.NewBundle(language.English)
|
||||
bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
|
||||
bundle.MustLoadMessageFile("translations/en.toml")
|
||||
bundle.LoadMessageFile("translations/de.toml")
|
||||
bundle.LoadMessageFile("translations/it.toml")
|
||||
bundle.LoadMessageFile("translations/es.toml")
|
||||
bundle.LoadMessageFile("translations/nl.toml")
|
||||
bundle.LoadMessageFile("translations/fr.toml")
|
||||
bundle.LoadMessageFile("translations/pt-br.toml")
|
||||
bundle.LoadMessageFile("translations/tr.toml")
|
||||
bundle.LoadMessageFile("translations/id.toml")
|
||||
bundle.LoadMessageFile("translations/ru.toml")
|
||||
return bundle
|
||||
}
|
||||
func Translate(languageCode string, MessgeID string) string {
|
||||
str, err := i18n.NewLocalizer(Bundle, languageCode).Localize(&i18n.LocalizeConfig{MessageID: MessgeID})
|
||||
if err != nil {
|
||||
log.Warnf("Error translating message %s: %s", MessgeID, err)
|
||||
}
|
||||
return str
|
||||
}
|
||||
@@ -2,12 +2,17 @@ package lnbits
|
||||
|
||||
import (
|
||||
"github.com/imroc/req"
|
||||
"time"
|
||||
)
|
||||
|
||||
// NewClient returns a new lnbits api client. Pass your API key and url here.
|
||||
func NewClient(key, url string) *Client {
|
||||
return &Client{
|
||||
url: url,
|
||||
// info: this header holds the ADMIN key for the entire API
|
||||
// it can be used to create wallets for example
|
||||
// if you want to check the balance of a user, use w.Inkey
|
||||
// if you want to make a payment, use w.Adminkey
|
||||
header: req.Header{
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
@@ -74,14 +79,18 @@ func (c *Client) CreateWallet(userId, walletName, adminId string) (wal Wallet, e
|
||||
return
|
||||
}
|
||||
err = resp.ToJSON(&wal)
|
||||
wal.Client = c
|
||||
return
|
||||
}
|
||||
|
||||
// Invoice creates an invoice associated with this wallet.
|
||||
func (c Client) Invoice(params InvoiceParams, w Wallet) (lntx BitInvoice, err error) {
|
||||
c.header["X-Api-Key"] = w.Adminkey
|
||||
resp, err := req.Post(c.url+"/api/v1/payments", w.header, req.BodyJSON(¶ms))
|
||||
func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx BitInvoice, 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.Post(c.url+"/api/v1/payments", invoiceHeader, req.BodyJSON(¶ms))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -99,8 +108,13 @@ func (c Client) Invoice(params InvoiceParams, w Wallet) (lntx BitInvoice, err er
|
||||
|
||||
// Info returns wallet information
|
||||
func (c Client) Info(w Wallet) (wtx Wallet, err error) {
|
||||
c.header["X-Api-Key"] = w.Adminkey
|
||||
resp, err := req.Get(w.url+"/api/v1/wallet", w.header, nil)
|
||||
// custom header with invoice key
|
||||
invoiceHeader := req.Header{
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"X-Api-Key": w.Inkey,
|
||||
}
|
||||
resp, err := req.Get(c.url+"/api/v1/wallet", invoiceHeader, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -135,9 +149,16 @@ func (c Client) Wallets(w User) (wtx []Wallet, err error) {
|
||||
}
|
||||
|
||||
// Pay pays a given invoice with funds from the wallet.
|
||||
func (c Client) Pay(params PaymentParams, w Wallet) (wtx BitInvoice, err error) {
|
||||
c.header["X-Api-Key"] = w.Adminkey
|
||||
resp, err := req.Post(c.url+"/api/v1/payments", w.header, req.BodyJSON(¶ms))
|
||||
func (w Wallet) Pay(params PaymentParams, c *Client) (wtx BitInvoice, err error) {
|
||||
// custom header with admin key
|
||||
adminHeader := req.Header{
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"X-Api-Key": w.Adminkey,
|
||||
}
|
||||
r := req.New()
|
||||
r.SetTimeout(time.Hour * 24)
|
||||
resp, err := r.Post(c.url+"/api/v1/payments", adminHeader, req.BodyJSON(¶ms))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
+68
-29
@@ -1,8 +1,15 @@
|
||||
package lnbits
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/btcsuite/btcd/btcec"
|
||||
|
||||
"github.com/imroc/req"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
@@ -13,31 +20,52 @@ 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"`
|
||||
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"`
|
||||
}
|
||||
type UserStateKey int
|
||||
|
||||
const (
|
||||
UserStateConfirmPayment = iota + 1
|
||||
UserStateConfirmSend
|
||||
UserStateLNURLEnterAmount
|
||||
UserStateConfirmLNURLPay
|
||||
UserEnterAmount
|
||||
UserHasEnteredAmount
|
||||
UserEnterUser
|
||||
UserHasEnteredUser
|
||||
UserEnterShopTitle
|
||||
UserStateShopItemSendPhoto
|
||||
UserStateShopItemSendTitle
|
||||
UserStateShopItemSendDescription
|
||||
UserStateShopItemSendPrice
|
||||
UserStateShopItemSendItemFile
|
||||
UserEnterShopsDescription
|
||||
)
|
||||
|
||||
type UserStateKey int
|
||||
|
||||
func (u *User) ResetState() {
|
||||
u.StateData = ""
|
||||
u.StateKey = 0
|
||||
}
|
||||
|
||||
type InvoiceParams struct {
|
||||
Out bool `json:"out"`
|
||||
Amount int64 `json:"amount"`
|
||||
Memo string `json:"memo"` // the invoice description.
|
||||
Webhook string `json:"webhook,omitempty"`
|
||||
Out bool `json:"out"` // must be True if invoice is payed, False if invoice is received
|
||||
Amount int64 `json:"amount"` // amount in MilliSatoshi
|
||||
Memo string `json:"memo,omitempty"` // the invoice memo.
|
||||
Webhook string `json:"webhook,omitempty"` // the webhook to fire back to when payment is received.
|
||||
DescriptionHash string `json:"description_hash,omitempty"` // the invoice description hash.
|
||||
}
|
||||
|
||||
type PaymentParams struct {
|
||||
@@ -70,7 +98,6 @@ func (err Error) Error() string {
|
||||
}
|
||||
|
||||
type Wallet struct {
|
||||
*Client `gorm:"-"`
|
||||
ID string `json:"id" gorm:"id"`
|
||||
Adminkey string `json:"adminkey"`
|
||||
Inkey string `json:"inkey"`
|
||||
@@ -82,19 +109,31 @@ type BitInvoice struct {
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
PaymentRequest string `json:"payment_request"`
|
||||
}
|
||||
type Webhook struct {
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending int `json:"pending"`
|
||||
Amount int `json:"amount"`
|
||||
Fee int `json:"fee"`
|
||||
Memo string `json:"memo"`
|
||||
Time int `json:"time"`
|
||||
Bolt11 string `json:"bolt11"`
|
||||
Preimage string `json:"preimage"`
|
||||
PaymentHash string `json:"payment_hash"`
|
||||
Extra struct {
|
||||
} `json:"extra"`
|
||||
WalletID string `json:"wallet_id"`
|
||||
Webhook string `json:"webhook"`
|
||||
WebhookStatus interface{} `json:"webhook_status"`
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
package lnbits
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
invoiceReceivedMessage = "⚡️ You've received %d sat."
|
||||
)
|
||||
|
||||
type WebhookServer struct {
|
||||
httpServer *http.Server
|
||||
bot *tb.Bot
|
||||
c *Client
|
||||
database *gorm.DB
|
||||
}
|
||||
|
||||
func NewWebhook(webhookServer string, bot *tb.Bot, client *Client, database *gorm.DB) *WebhookServer {
|
||||
if !strings.Contains(webhookServer, "://") {
|
||||
log.Fatal("invalid webhook server configuration. please add a scheme.")
|
||||
}
|
||||
_, port, err := net.SplitHostPort(strings.Split(webhookServer, "//")[1])
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
srv := &http.Server{
|
||||
Addr: fmt.Sprintf("0.0.0.0:%s", port),
|
||||
// Good practice: enforce timeouts for servers you create!
|
||||
WriteTimeout: 15 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
}
|
||||
apiServer := &WebhookServer{
|
||||
c: client,
|
||||
database: database,
|
||||
bot: bot,
|
||||
httpServer: srv,
|
||||
}
|
||||
apiServer.httpServer.Handler = apiServer.newRouter()
|
||||
go apiServer.httpServer.ListenAndServe()
|
||||
return apiServer
|
||||
}
|
||||
|
||||
func (w *WebhookServer) GetUserByWalletId(walletId string) (*User, error) {
|
||||
user := &User{}
|
||||
tx := w.database.Where("wallet_id = ?", walletId).First(user)
|
||||
if tx.Error != nil {
|
||||
return user, tx.Error
|
||||
}
|
||||
user.Wallet.Client = w.c
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (w *WebhookServer) newRouter() *mux.Router {
|
||||
router := mux.NewRouter()
|
||||
router.HandleFunc("/", w.receive).Methods(http.MethodPost)
|
||||
return router
|
||||
}
|
||||
|
||||
func (w WebhookServer) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
depositEvent := Webhook{}
|
||||
request.Header.Del("content-length")
|
||||
err := json.NewDecoder(request.Body).Decode(&depositEvent)
|
||||
if err != nil {
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
user, err := w.GetUserByWalletId(depositEvent.WalletID)
|
||||
if err != nil {
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
log.Infoln(fmt.Sprintf("[WebHook] User %s (%d) received invoice of %d sat.", user.Telegram.Username, user.Telegram.ID, depositEvent.Amount/1000))
|
||||
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(invoiceReceivedMessage, depositEvent.Amount/1000))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
writer.WriteHeader(200)
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"net/http"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
httpServer *http.Server
|
||||
bot *tb.Bot
|
||||
c *lnbits.Client
|
||||
database *gorm.DB
|
||||
buntdb *storage.DB
|
||||
}
|
||||
|
||||
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"`
|
||||
WalletID string `json:"wallet_id"`
|
||||
Webhook string `json:"webhook"`
|
||||
WebhookStatus interface{} `json:"webhook_status"`
|
||||
}
|
||||
|
||||
func NewServer(bot *telegram.TipBot) *Server {
|
||||
srv := &http.Server{
|
||||
Addr: internal.Configuration.Lnbits.WebhookServerUrl.Host,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
}
|
||||
apiServer := &Server{
|
||||
c: bot.Client,
|
||||
database: bot.Database,
|
||||
bot: bot.Telegram,
|
||||
httpServer: srv,
|
||||
buntdb: bot.Bunt,
|
||||
}
|
||||
apiServer.httpServer.Handler = apiServer.newRouter()
|
||||
go apiServer.httpServer.ListenAndServe()
|
||||
log.Infof("[Webhook] Server started at %s", internal.Configuration.Lnbits.WebhookServerUrl)
|
||||
return apiServer
|
||||
}
|
||||
|
||||
func (w *Server) GetUserByWalletId(walletId string) (*lnbits.User, error) {
|
||||
user := &lnbits.User{}
|
||||
tx := w.database.Where("wallet_id = ?", walletId).First(user)
|
||||
if tx.Error != nil {
|
||||
return user, tx.Error
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (w *Server) newRouter() *mux.Router {
|
||||
router := mux.NewRouter()
|
||||
router.HandleFunc("/", w.receive).Methods(http.MethodPost)
|
||||
return router
|
||||
}
|
||||
|
||||
func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
log.Debugln("[Webhook] Received request")
|
||||
webhookEvent := Webhook{}
|
||||
// need to delete the header otherwise the Decode will fail
|
||||
request.Header.Del("content-length")
|
||||
err := json.NewDecoder(request.Body).Decode(&webhookEvent)
|
||||
if err != nil {
|
||||
log.Errorf("[Webhook] Error decoding request: %s", err.Error())
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
user, err := w.GetUserByWalletId(webhookEvent.WalletID)
|
||||
if err != nil {
|
||||
log.Errorf("[Webhook] Error getting user: %s", err.Error())
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
log.Infoln(fmt.Sprintf("[⚡️ WebHook] User %s (%d) received invoice of %d sat.", telegram.GetUserStr(user.Telegram), user.Telegram.ID, webhookEvent.Amount/1000))
|
||||
|
||||
writer.WriteHeader(200)
|
||||
|
||||
// trigger invoice events
|
||||
txInvoiceEvent := &telegram.InvoiceEvent{Invoice: &telegram.Invoice{PaymentHash: webhookEvent.PaymentHash}}
|
||||
err = w.buntdb.Get(txInvoiceEvent)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
} else {
|
||||
// do something with the event
|
||||
if c := telegram.InvoiceCallback[txInvoiceEvent.Callback]; c != nil {
|
||||
c(txInvoiceEvent)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package lndhub
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/api"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type LndHub struct {
|
||||
database *gorm.DB
|
||||
}
|
||||
|
||||
func New(bot *telegram.TipBot) LndHub {
|
||||
return LndHub{database: bot.Database}
|
||||
}
|
||||
func (w LndHub) Handle(writer http.ResponseWriter, request *http.Request) {
|
||||
auth := request.Header.Get("Authorization")
|
||||
|
||||
// check if the user is banned
|
||||
if auth != "" {
|
||||
_, password, ok := parseBearerAuth(auth)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// first we make sure that the password is not already "banned_"
|
||||
if strings.Contains(password, "_") || strings.HasPrefix(password, "banned_") {
|
||||
log.Warnf("[LNDHUB] Banned user %s. Not forwarding request", password)
|
||||
return
|
||||
}
|
||||
// then we check whether the "normal" password provided is in the database (it should be not if the user is banned)
|
||||
user := &lnbits.User{}
|
||||
tx := w.database.Where("wallet_adminkey = ? COLLATE NOCASE", password).First(user)
|
||||
if tx.Error != nil {
|
||||
log.Warnf("[LNDHUB] Could not get wallet admin key %s: %v", password, tx.Error)
|
||||
return
|
||||
}
|
||||
log.Debugf("[LNDHUB] User: %s", telegram.GetUserStr(user.Telegram))
|
||||
}
|
||||
// if not, proxy the request
|
||||
api.Proxy(writer, request, internal.Configuration.Lnbits.Url)
|
||||
}
|
||||
|
||||
// parseBearerAuth parses an HTTP Basic Authentication string.
|
||||
// "Bearer QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
|
||||
func parseBearerAuth(auth string) (username, password string, ok bool) {
|
||||
const prefix = "Bearer "
|
||||
// Case insensitive prefix match. See Issue 22736.
|
||||
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
|
||||
return
|
||||
}
|
||||
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
cs := string(c)
|
||||
s := strings.IndexByte(cs, ':')
|
||||
if s < 0 {
|
||||
return
|
||||
}
|
||||
return cs[:s], cs[s+1:], true
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
package lnurl
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/api"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
"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
|
||||
}
|
||||
|
||||
func New(bot *telegram.TipBot) Lnurl {
|
||||
return Lnurl{
|
||||
c: bot.Client,
|
||||
database: bot.Database,
|
||||
callbackHostname: internal.Configuration.Bot.LNURLHostUrl,
|
||||
WebhookServer: internal.Configuration.Lnbits.WebhookServer,
|
||||
buntdb: bot.Bunt,
|
||||
telegram: bot.Telegram,
|
||||
cache: bot.Cache,
|
||||
}
|
||||
}
|
||||
func (lnurlInvoice Invoice) Key() string {
|
||||
return fmt.Sprintf("lnurl-p:%s", lnurlInvoice.PaymentHash)
|
||||
}
|
||||
|
||||
func (w Lnurl) Handle(writer http.ResponseWriter, request *http.Request) {
|
||||
var err error
|
||||
var response interface{}
|
||||
username := mux.Vars(request)["username"]
|
||||
if request.URL.RawQuery == "" {
|
||||
response, err = w.serveLNURLpFirst(username)
|
||||
} else {
|
||||
stringAmount := request.FormValue("amount")
|
||||
if stringAmount == "" {
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Form value 'amount' is not set"))
|
||||
return
|
||||
}
|
||||
amount, parseError := strconv.Atoi(stringAmount)
|
||||
if parseError != nil {
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int %v", parseError))
|
||||
return
|
||||
}
|
||||
comment := request.FormValue("comment")
|
||||
if len(comment) > CommentAllowed {
|
||||
api.NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] 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)
|
||||
}
|
||||
// check if error was returned from first or second handlers
|
||||
if err != nil {
|
||||
// log the error
|
||||
log.Errorf("[LNURL] %v", err.Error())
|
||||
if response != nil {
|
||||
// there is a valid error response
|
||||
err = api.WriteResponse(writer, response)
|
||||
if err != nil {
|
||||
api.NotFoundHandler(writer, err)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
// no error from first or second handler
|
||||
err = api.WriteResponse(writer, response)
|
||||
if err != nil {
|
||||
api.NotFoundHandler(writer, err)
|
||||
}
|
||||
}
|
||||
func (w Lnurl) getMetaDataCached(username string) lnurl.Metadata {
|
||||
key := fmt.Sprintf("lnurl_metadata_%s", username)
|
||||
|
||||
// load metadata from cache
|
||||
if m, err := w.cache.Get(key); err == nil {
|
||||
return m.(lnurl.Metadata)
|
||||
}
|
||||
|
||||
// otherwise, create new metadata
|
||||
metadata := w.metaData(username)
|
||||
|
||||
// load the user profile picture
|
||||
if internal.Configuration.Bot.LNURLSendImage {
|
||||
// get the user from the database
|
||||
user, tx := findUser(w.database, username)
|
||||
if tx.Error == nil && user.Telegram != nil {
|
||||
addImageToMetaData(w.telegram, &metadata, username, user.Telegram)
|
||||
}
|
||||
}
|
||||
|
||||
// save into cache
|
||||
runtime.IgnoreError(w.cache.Set(key, metadata, &store.Options{Expiration: 30 * time.Minute}))
|
||||
return metadata
|
||||
}
|
||||
|
||||
// serveLNURLpFirst serves the first part of the LNURLp protocol with the endpoint
|
||||
// to call and the metadata that matches the description hash of the second response
|
||||
func (w Lnurl) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error) {
|
||||
log.Infof("[LNURL] Serving endpoint for user %s", username)
|
||||
callbackURL, err := url.Parse(fmt.Sprintf("%s/%s/%s", w.callbackHostname.String(), Endpoint, username))
|
||||
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,
|
||||
Callback: callbackURL.String(),
|
||||
MinSendable: MinSendable,
|
||||
MaxSendable: MaxSendable,
|
||||
EncodedMetadata: metadata.Encode(),
|
||||
CommentAllowed: CommentAllowed,
|
||||
PayerData: &lnurl.PayerDataSpec{
|
||||
FreeName: &lnurl.PayerDataItemSpec{},
|
||||
LightningAddress: &lnurl.PayerDataItemSpec{},
|
||||
Email: &lnurl.PayerDataItemSpec{},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// serveLNURLpSecond serves the second LNURL response with the payment request with the correct description hash
|
||||
func (w Lnurl) serveLNURLpSecond(username string, amount_msat int64, comment string, payerData lnurl.PayerDataValues) (*lnurl.LNURLPayValues, error) {
|
||||
log.Infof("[LNURL] Serving invoice for user %s", username)
|
||||
if amount_msat < MinSendable || amount_msat > MaxSendable {
|
||||
// amount is not ok
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.StatusError,
|
||||
Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", MinSendable, MinSendable)},
|
||||
}, fmt.Errorf("amount out of bounds")
|
||||
}
|
||||
// check comment length
|
||||
if len(comment) > CommentAllowed {
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.StatusError,
|
||||
Reason: fmt.Sprintf("Comment too long (max: %d characters).", CommentAllowed)},
|
||||
}, fmt.Errorf("comment too long")
|
||||
}
|
||||
user, tx := findUser(w.database, username)
|
||||
if tx.Error != nil {
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.StatusError,
|
||||
Reason: fmt.Sprintf("Invalid user.")},
|
||||
}, fmt.Errorf("[GetUser] Couldn't fetch user info from database: %v", tx.Error)
|
||||
}
|
||||
if user.Wallet == nil {
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.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
|
||||
|
||||
// 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))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Amount: amount_msat / 1000,
|
||||
Out: false,
|
||||
DescriptionHash: descriptionHash,
|
||||
Webhook: w.WebhookServer},
|
||||
w.c)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("[serveLNURLpSecond] Couldn't create invoice: %v", err.Error())
|
||||
resp = &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: api.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)
|
||||
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,
|
||||
}))
|
||||
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: api.StatusOk},
|
||||
PR: invoice.PaymentRequest,
|
||||
Routes: make([]struct{}, 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[:])
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
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 ""
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package price
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
type PriceWatcher struct {
|
||||
client *http.Client
|
||||
UpdateInterval time.Duration
|
||||
Currencies map[string]string
|
||||
Exchanges map[string]func(string) (float64, error)
|
||||
}
|
||||
|
||||
var (
|
||||
Price map[string]float64
|
||||
P *PriceWatcher
|
||||
)
|
||||
|
||||
func NewPriceWatcher() *PriceWatcher {
|
||||
pricewatcher := &PriceWatcher{
|
||||
client: &http.Client{
|
||||
Timeout: time.Second * time.Duration(5),
|
||||
},
|
||||
// attention: $ must come after other $-denominated currencies like R$
|
||||
Currencies: map[string]string{
|
||||
"EUR": "€",
|
||||
"GBP": "£",
|
||||
"JPY": "¥",
|
||||
"BRL": "R$",
|
||||
"MXN": "MX$",
|
||||
"USD": "$",
|
||||
"RUB": "₽",
|
||||
"TRY": "₺",
|
||||
"INR": "₹",
|
||||
},
|
||||
Exchanges: make(map[string]func(string) (float64, error), 0),
|
||||
UpdateInterval: time.Second * time.Duration(30),
|
||||
}
|
||||
pricewatcher.Exchanges["coinbase"] = pricewatcher.GetCoinbasePrice
|
||||
pricewatcher.Exchanges["bitfinex"] = pricewatcher.GetBitfinexPrice
|
||||
Price = make(map[string]float64, 0)
|
||||
log.Infof("[PriceWatcher] Watcher started")
|
||||
P = pricewatcher
|
||||
return pricewatcher
|
||||
}
|
||||
|
||||
func (p *PriceWatcher) Start() {
|
||||
go p.Watch()
|
||||
}
|
||||
|
||||
func (p *PriceWatcher) Watch() error {
|
||||
for {
|
||||
for currency, _ := range p.Currencies {
|
||||
avg_price := 0.0
|
||||
n_responses := 0
|
||||
for _, getPrice := range p.Exchanges {
|
||||
fprice, err := getPrice(currency)
|
||||
if err != nil {
|
||||
// log.Debug(err)
|
||||
// if one exchanges is down, use the next
|
||||
continue
|
||||
}
|
||||
n_responses++
|
||||
avg_price += 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])
|
||||
}
|
||||
time.Sleep(p.UpdateInterval)
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
return 0, err
|
||||
}
|
||||
bodyBytes, err := ioutil.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
log.Debug(err)
|
||||
return 0, err
|
||||
}
|
||||
price := gjson.Get(string(bodyBytes), "data.amount")
|
||||
if len(price.String()) > 0 {
|
||||
fprice, err := strconv.ParseFloat(strings.TrimSpace(price.String()), 64)
|
||||
if err != nil {
|
||||
log.Debug(err)
|
||||
return 0, err
|
||||
}
|
||||
return fprice, nil
|
||||
} else {
|
||||
return 0, fmt.Errorf("no price")
|
||||
}
|
||||
}
|
||||
|
||||
func (p *PriceWatcher) GetBitfinexPrice(currency string) (float64, error) {
|
||||
var bitfinexCurrencyToPair = map[string]string{"USD": "btcusd", "EUR": "btceur", "GBP": "btcusd", "JPY": "btcjpy"}
|
||||
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 {
|
||||
return 0, err
|
||||
}
|
||||
bodyBytes, err := ioutil.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
log.Debug(err)
|
||||
return 0, err
|
||||
}
|
||||
price := gjson.Get(string(bodyBytes), "last_price")
|
||||
if len(price.String()) > 0 {
|
||||
fprice, err := strconv.ParseFloat(strings.TrimSpace(price.String()), 64)
|
||||
if err != nil {
|
||||
log.Debug(err)
|
||||
return 0, err
|
||||
}
|
||||
return fprice, nil
|
||||
} else {
|
||||
return 0, fmt.Errorf("no price")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package runtime
|
||||
|
||||
import log "github.com/sirupsen/logrus"
|
||||
|
||||
// accepts error and logs error message. Used to prevent warnings when errors not caught.
|
||||
func IgnoreError(err error) {
|
||||
if err != nil {
|
||||
log.WithFields(log.Fields{"module": "[ERROR]", "error": err.Error()}).Errorf("catching ignored error")
|
||||
}
|
||||
}
|
||||
func IgnoreErrorMultiReturn(i interface{}, err error) {
|
||||
if err != nil {
|
||||
log.WithFields(log.Fields{"module": "[ERROR]", "error": err.Error()}).Errorf("catching ignored error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
"time"
|
||||
)
|
||||
|
||||
var tickerMap cmap.ConcurrentMap
|
||||
|
||||
func init() {
|
||||
tickerMap = cmap.New()
|
||||
}
|
||||
|
||||
var defaultTickerCoolDown = time.Second * 10
|
||||
|
||||
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
|
||||
type ResettableFunctionTicker struct {
|
||||
Ticker *time.Ticker
|
||||
ResetChan chan struct{} // channel used to reset the ticker
|
||||
duration time.Duration
|
||||
Started bool
|
||||
name string
|
||||
}
|
||||
type ResettableFunctionTickerOption func(*ResettableFunctionTicker)
|
||||
|
||||
func WithDuration(d time.Duration) ResettableFunctionTickerOption {
|
||||
return func(a *ResettableFunctionTicker) {
|
||||
a.duration = d
|
||||
}
|
||||
}
|
||||
func RemoveTicker(name string) {
|
||||
tickerMap.Remove(name)
|
||||
}
|
||||
func GetTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
|
||||
|
||||
if t, ok := tickerMap.Get(name); ok {
|
||||
return t.(*ResettableFunctionTicker)
|
||||
} else {
|
||||
t := NewResettableFunctionTicker(name, option...)
|
||||
tickerMap.Set(name, t)
|
||||
return t
|
||||
}
|
||||
}
|
||||
func NewResettableFunctionTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
|
||||
t := &ResettableFunctionTicker{
|
||||
ResetChan: make(chan struct{}, 1),
|
||||
name: name,
|
||||
}
|
||||
|
||||
for _, opt := range option {
|
||||
opt(t)
|
||||
}
|
||||
if t.duration == 0 {
|
||||
t.duration = defaultTickerCoolDown
|
||||
}
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *ResettableFunctionTicker) Do(f func()) {
|
||||
t.Started = true
|
||||
tickerMap.Set(t.name, t)
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-t.Ticker.C:
|
||||
// ticker delivered signal. do function f
|
||||
f()
|
||||
return
|
||||
case <-t.ResetChan:
|
||||
// reset signal received. creating new ticker.
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package once
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var onceMap cmap.ConcurrentMap
|
||||
|
||||
func init() {
|
||||
onceMap = cmap.New()
|
||||
}
|
||||
|
||||
func New(objectKey string) {
|
||||
onceMap.Set(objectKey, cmap.New())
|
||||
}
|
||||
|
||||
// Once creates a map of keys k1 with a map of keys k2.
|
||||
// The idea is that an object with ID k1 can create a list of users k2
|
||||
// that have already interacted with the object. If the user k2 is in the list,
|
||||
// the object is not allowed to accessed again.
|
||||
func Once(k1, k2 string) error {
|
||||
i, ok := onceMap.Get(k1)
|
||||
if ok {
|
||||
return setOrReturn(i.(cmap.ConcurrentMap), k2)
|
||||
}
|
||||
userMap := cmap.New()
|
||||
onceMap.Set(k1, userMap)
|
||||
log.Tracef("[Once] Added key %s to onceMap (len=%d)", k1, len(onceMap.Keys()))
|
||||
return setOrReturn(userMap, k2)
|
||||
}
|
||||
|
||||
// setOrReturn sets the key k2 in the map i if it is not already set.
|
||||
func setOrReturn(objectMap cmap.ConcurrentMap, k2 string) error {
|
||||
if _, ok := objectMap.Get(k2); ok {
|
||||
return fmt.Errorf("[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()))
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/buntdb"
|
||||
)
|
||||
|
||||
// Storable items must provide a function to retrieve the database key
|
||||
type Storable interface {
|
||||
Key() string
|
||||
}
|
||||
|
||||
type DB struct {
|
||||
*buntdb.DB
|
||||
}
|
||||
|
||||
func NewBunt(filePath string) *DB {
|
||||
db, err := buntdb.Open(filePath)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
return &DB{db}
|
||||
}
|
||||
|
||||
// Exists checks is storable item exists
|
||||
func (db *DB) Exists(storable Storable) (ok bool, err error) {
|
||||
ok = false
|
||||
err = db.View(func(tx *buntdb.Tx) error {
|
||||
_, err := tx.Get(storable.Key())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if err == buntdb.ErrNotFound {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
ok = true
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
// Get a storable item
|
||||
func (db *DB) Get(object Storable) error {
|
||||
err := db.View(func(tx *buntdb.Tx) error {
|
||||
val, err := tx.Get(object.Key())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = json.Unmarshal([]byte(val), object)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// Set a storable item.
|
||||
func (db *DB) Set(object Storable) error {
|
||||
err := db.Update(func(tx *buntdb.Tx) error {
|
||||
b, err := json.Marshal(object)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, _, err = tx.Set(object.Key(), string(b), nil)
|
||||
|
||||
return err
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete a storable item.
|
||||
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
|
||||
}
|
||||
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,57 @@
|
||||
package str
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
)
|
||||
|
||||
var markdownV2Escapes = []string{"_", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!"}
|
||||
var markdownEscapes = []string{"_", "*", "`", "["}
|
||||
|
||||
func MarkdownV2Escape(s string) string {
|
||||
for _, esc := range markdownV2Escapes {
|
||||
if strings.Contains(s, esc) {
|
||||
s = strings.Replace(s, esc, fmt.Sprintf("\\%s", esc), -1)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func MarkdownEscape(s string) string {
|
||||
for _, esc := range markdownEscapes {
|
||||
if strings.Contains(s, esc) {
|
||||
s = strings.Replace(s, esc, fmt.Sprintf("\\%s", esc), -1)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func Int32Hash(s string) uint32 {
|
||||
h := fnv.New32a()
|
||||
h.Write([]byte(s))
|
||||
return h.Sum32()
|
||||
}
|
||||
|
||||
func Int64Hash(s string) uint64 {
|
||||
h := fnv.New64a()
|
||||
h.Write([]byte(s))
|
||||
return h.Sum64()
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"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"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/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")
|
||||
}
|
||||
output = strings.Split(input, " ")[which]
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func decodeAmountFromCommand(input string) (amount int64, err error) {
|
||||
if len(strings.Split(input, " ")) < 2 {
|
||||
errmsg := "message doesn't contain any amount"
|
||||
// log.Errorln(errmsg)
|
||||
return 0, fmt.Errorf(errmsg)
|
||||
}
|
||||
amount, err = getAmount(strings.Split(input, " ")[1])
|
||||
return amount, err
|
||||
}
|
||||
|
||||
func getAmount(input string) (amount int64, err error) {
|
||||
// convert something like 1.2k into 1200
|
||||
if strings.HasSuffix(strings.ToLower(input), "k") {
|
||||
fmount, err := strconv.ParseFloat(strings.TrimSpace(input[:len(input)-1]), 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
amount = int64(fmount * 1000)
|
||||
return amount, err
|
||||
}
|
||||
|
||||
// convert fiat currencies to satoshis
|
||||
for currency, symbol := range price.P.Currencies {
|
||||
if strings.HasPrefix(input, symbol) || strings.HasSuffix(input, symbol) || // for 1$ and $1
|
||||
strings.HasPrefix(strings.ToLower(input), strings.ToLower(currency)) || // for USD1
|
||||
strings.HasSuffix(strings.ToLower(input), strings.ToLower(currency)) { // for 1USD
|
||||
numeric_string := ""
|
||||
numeric_string = strings.Replace(input, symbol, "", 1) // for symbol like $
|
||||
numeric_string = strings.Replace(strings.ToLower(numeric_string), strings.ToLower(currency), "", 1) // for 1USD
|
||||
fmount, err := strconv.ParseFloat(numeric_string, 64)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return 0, err
|
||||
}
|
||||
if !(price.Price[currency] > 0) {
|
||||
return 0, fmt.Errorf("price is zero")
|
||||
}
|
||||
amount = int64(fmount / price.Price[currency] * float64(100_000_000))
|
||||
return amount, nil
|
||||
}
|
||||
}
|
||||
|
||||
// use plain integer as satoshis
|
||||
amount, err = strconv.ParseInt(input, 10, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if amount <= 0 {
|
||||
return 0, fmt.Errorf("amount must be greater than 0")
|
||||
}
|
||||
return amount, err
|
||||
}
|
||||
|
||||
type EnterAmountStateData struct {
|
||||
ID string `json:"ID"` // holds the ID of the tx object in bunt db
|
||||
Type string `json:"Type"` // holds type of the tx in bunt db (needed for type checking)
|
||||
Amount int64 `json:"Amount"` // holds the amount entered by the user mSat
|
||||
AmountMin int64 `json:"AmountMin"` // holds the minimum amount that needs to be entered mSat
|
||||
AmountMax int64 `json:"AmountMax"` // holds the maximum amount that needs to be entered mSat
|
||||
OiringalCommand string `json:"OiringalCommand"` // hold the originally entered command for evtl later use
|
||||
}
|
||||
|
||||
func (bot *TipBot) askForAmount(ctx context.Context, id string, eventType string, amountMin int64, amountMax int64, originalCommand string) (enterAmountStateData *EnterAmountStateData, err error) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return // errors.New("user has no wallet"), 0
|
||||
}
|
||||
enterAmountStateData = &EnterAmountStateData{
|
||||
ID: id,
|
||||
Type: eventType,
|
||||
AmountMin: amountMin,
|
||||
AmountMax: amountMax,
|
||||
OiringalCommand: originalCommand,
|
||||
}
|
||||
// set LNURLPayParams in the state of the user
|
||||
stateDataJson, err := json.Marshal(enterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserEnterAmount, string(stateDataJson))
|
||||
askAmountText := Translate(ctx, "enterAmountMessage")
|
||||
if amountMin > 0 && amountMax >= amountMin {
|
||||
askAmountText = fmt.Sprintf(Translate(ctx, "enterAmountRangeMessage"), enterAmountStateData.AmountMin/1000, enterAmountStateData.AmountMax/1000)
|
||||
}
|
||||
// Let the user enter an amount and return
|
||||
bot.trySendMessage(user.Telegram, askAmountText, tb.ForceReply)
|
||||
return
|
||||
}
|
||||
|
||||
// enterAmountHandler is invoked in anyTextHandler when the user needs to enter an amount
|
||||
// the amount is then stored as an entry in the user's stateKey in the user database
|
||||
// any other handler that relies on this, needs to load the resulting amount from the database
|
||||
func (bot *TipBot) enterAmountHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
|
||||
if !(user.StateKey == lnbits.UserEnterAmount) {
|
||||
ResetUserState(user, bot)
|
||||
return ctx, fmt.Errorf("invalid statekey")
|
||||
}
|
||||
|
||||
var EnterAmountStateData EnterAmountStateData
|
||||
err := json.Unmarshal([]byte(user.StateData), &EnterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorf("[enterAmountHandler] %s", err.Error())
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
amount, err := getAmount(m.Text)
|
||||
if err != nil {
|
||||
log.Warnf("[enterAmountHandler] %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
|
||||
ResetUserState(user, bot)
|
||||
return ctx, err
|
||||
}
|
||||
// amount not in allowed range from LNURL
|
||||
if EnterAmountStateData.AmountMin > 0 && EnterAmountStateData.AmountMax >= EnterAmountStateData.AmountMin && // this line checks whether min_max is set at all
|
||||
(amount > int64(EnterAmountStateData.AmountMax/1000) || amount < int64(EnterAmountStateData.AmountMin/1000)) { // this line then checks whether the amount is in the range
|
||||
err = fmt.Errorf("amount not in range")
|
||||
log.Warnf("[enterAmountHandler] %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), EnterAmountStateData.AmountMin/1000, EnterAmountStateData.AmountMax/1000))
|
||||
ResetUserState(user, bot)
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
|
||||
// find out which type the object in bunt has waiting for an amount
|
||||
// we stored this in the EnterAmountStateData before
|
||||
switch EnterAmountStateData.Type {
|
||||
case "LnurlPayState":
|
||||
tx := &LnurlPayState{Base: storage.New(storage.ID(EnterAmountStateData.ID))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
LnurlPayState := sn.(*LnurlPayState)
|
||||
LnurlPayState.Amount = amount * 1000 // mSat
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(LnurlPayState.Set(LnurlPayState, bot.Bunt))
|
||||
|
||||
EnterAmountStateData.Amount = int64(amount) * 1000 // mSat
|
||||
StateDataJson, err := json.Marshal(EnterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
}
|
||||
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)
|
||||
case "CreateInvoiceState":
|
||||
m.Text = fmt.Sprintf("/invoice %d", amount)
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
return bot.invoiceHandler(ctx, m)
|
||||
case "CreateDonationState":
|
||||
m.Text = fmt.Sprintf("/donate %d", amount)
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
return bot.donationHandler(ctx, m)
|
||||
case "CreateSendState":
|
||||
splits := strings.SplitAfterN(EnterAmountStateData.OiringalCommand, " ", 2)
|
||||
if len(splits) > 1 {
|
||||
m.Text = fmt.Sprintf("/send %d %s", amount, splits[1])
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
return bot.sendHandler(ctx, m)
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
default:
|
||||
ResetUserState(user, bot)
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot *TipBot) balanceHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
// check and print all commands
|
||||
if len(m.Text) > 0 {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
}
|
||||
|
||||
// reply only in private message
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
// first check whether the user is initialized
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
|
||||
if !user.Initialized {
|
||||
return bot.startHandler(ctx, m)
|
||||
}
|
||||
|
||||
usrStr := GetUserStr(m.Sender)
|
||||
balance, err := bot.GetUserBalance(user)
|
||||
if err != nil {
|
||||
log.Errorf("[/balance] Error fetching %s's balance: %s", usrStr, err)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "balanceErrorMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
log.Infof("[/balance] %s's balance: %d sat\n", usrStr, balance)
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "balanceMessage"), balance))
|
||||
return ctx, nil
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
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"
|
||||
|
||||
"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"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type TipBot struct {
|
||||
Database *gorm.DB
|
||||
Bunt *storage.DB
|
||||
ShopBunt *storage.DB
|
||||
logger *gorm.DB
|
||||
Telegram *tb.Bot
|
||||
Client *lnbits.Client
|
||||
limiter map[string]limiter.Limiter
|
||||
Cache
|
||||
}
|
||||
type Cache struct {
|
||||
*store.GoCacheStore
|
||||
}
|
||||
|
||||
var (
|
||||
botWalletInitialisation = sync.Once{}
|
||||
telegramHandlerRegistration = sync.Once{}
|
||||
)
|
||||
|
||||
// NewBot migrates data and creates a new bot
|
||||
func NewBot() TipBot {
|
||||
gocacheClient := gocache.New(5*time.Minute, 10*time.Minute)
|
||||
gocacheStore := store.NewGoCache(gocacheClient, nil)
|
||||
// create sqlite databases
|
||||
db, txLogger := 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),
|
||||
Telegram: newTelegramBot(),
|
||||
Cache: Cache{GoCacheStore: gocacheStore},
|
||||
}
|
||||
}
|
||||
|
||||
// newTelegramBot will create a new Telegram bot.
|
||||
func newTelegramBot() *tb.Bot {
|
||||
tgb, err := tb.NewBot(tb.Settings{
|
||||
Token: internal.Configuration.Telegram.ApiKey,
|
||||
Poller: &tb.LongPoller{Timeout: 60 * time.Second},
|
||||
ParseMode: tb.ModeMarkdown,
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return tgb
|
||||
}
|
||||
|
||||
// initBotWallet will create / initialize the bot wallet
|
||||
// todo -- may want to derive user wallets from this specific bot wallet (master wallet), since lnbits usermanager extension is able to do that.
|
||||
func (bot TipBot) initBotWallet() error {
|
||||
botWalletInitialisation.Do(func() {
|
||||
_, err := bot.initWallet(bot.Telegram.Me)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[initBotWallet] Could not initialize bot wallet: %s", err.Error()))
|
||||
return
|
||||
}
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// GracefulShutdown will gracefully shutdown the bot
|
||||
// It will wait for all mutex locks to unlock before shutdown.
|
||||
func (bot *TipBot) GracefulShutdown() {
|
||||
t := time.NewTicker(time.Second * 10)
|
||||
log.Infof("[shutdown] Graceful shutdown (timeout=10s).")
|
||||
for {
|
||||
select {
|
||||
case <-t.C:
|
||||
// timer expired
|
||||
log.Infof("[shutdown] Graceful shutdown timeout reached. Forcing shutdown.")
|
||||
return
|
||||
default:
|
||||
// check if all mutex locks are unlocked
|
||||
if mutex.IsEmpty() {
|
||||
log.Infof("[shutdown] Graceful shutdown successful.")
|
||||
return
|
||||
}
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
log.Tracef("[shutdown] Trying graceful shutdown...")
|
||||
}
|
||||
}
|
||||
|
||||
// Start will initialize the Telegram bot and lnbits.
|
||||
func (bot *TipBot) Start() {
|
||||
log.Infof("[Telegram] Authorized on account @%s", bot.Telegram.Me.Username)
|
||||
// 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()
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/database"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"github.com/tidwall/buntdb"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
MessageOrderedByReplyToFrom = "message.reply_to_message.from.id"
|
||||
TipTooltipKeyPattern = "tip-tool-tip:*"
|
||||
)
|
||||
|
||||
func createBunt(file string) *storage.DB {
|
||||
// create bunt database
|
||||
bunt := storage.NewBunt(file)
|
||||
// create bunt database index for ascending (searching) TipTooltips
|
||||
err := bunt.CreateIndex(MessageOrderedByReplyToFrom, TipTooltipKeyPattern, buntdb.IndexJSON(MessageOrderedByReplyToFrom))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return bunt
|
||||
}
|
||||
|
||||
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 ...")
|
||||
// run the migration on anon_id
|
||||
err = database.MigrateAnonIdInt32Hash(db)
|
||||
}
|
||||
|
||||
// anon_id_sha256 migration (2022-01-01)
|
||||
if !db.Migrator().HasColumn(&lnbits.User{}, "anon_id_sha256") {
|
||||
// first we need to auto migrate the user. This will create anon_id column
|
||||
err = db.AutoMigrate(&lnbits.User{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.Info("Running anon_id_sha256 database migrations ...")
|
||||
// run the migration on anon_id
|
||||
err = database.MigrateAnonIdSha265Hash(db)
|
||||
}
|
||||
|
||||
// uuid migration (2022-02-11)
|
||||
if !db.Migrator().HasColumn(&lnbits.User{}, "uuid") {
|
||||
// first we need to auto migrate the user. This will create uuid column
|
||||
err = db.AutoMigrate(&lnbits.User{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.Info("Running UUID database migrations ...")
|
||||
// run the migration on uuid
|
||||
err = database.MigrateUUIDSha265Hash(db)
|
||||
}
|
||||
|
||||
// todo -- add more database field migrations here in the future
|
||||
return err
|
||||
}
|
||||
|
||||
func AutoMigration() (db *gorm.DB, txLogger *gorm.DB) {
|
||||
orm, err := gorm.Open(sqlite.Open(internal.Configuration.Database.DbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
if err != nil {
|
||||
panic("Initialize orm failed.")
|
||||
}
|
||||
err = ColumnMigrationTasks(orm)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = orm.AutoMigrate(&lnbits.User{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
txLogger, err = gorm.Open(sqlite.Open(internal.Configuration.Database.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
if err != nil {
|
||||
panic("Initialize orm failed.")
|
||||
}
|
||||
err = txLogger.AutoMigrate(&Transaction{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return orm, txLogger
|
||||
}
|
||||
|
||||
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
|
||||
if toUserDb.Wallet == nil {
|
||||
err = fmt.Errorf("%s | user @%s has no wallet", tx.Error, toUserStrWithoutAt)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return toUserDb, nil
|
||||
}
|
||||
func getCachedUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
user := &lnbits.User{Name: strconv.FormatInt(u.ID, 10)}
|
||||
if us, err := bot.Cache.Get(user.Name); err == nil {
|
||||
return us.(*lnbits.User), nil
|
||||
}
|
||||
user.Telegram = u
|
||||
return user, gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
// GetLnbitsUser will not update the user in Database.
|
||||
// this is required, because fetching lnbits.User from a incomplete tb.User
|
||||
// will update the incomplete (partial) user in storage.
|
||||
// this function will accept users like this:
|
||||
// &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)}
|
||||
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())
|
||||
log.Warnln(errmsg)
|
||||
user.Telegram = u
|
||||
return user, tx.Error
|
||||
}
|
||||
// todo -- unblock this !
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// GetUser from Telegram user. Update the user if user information changed.
|
||||
func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
var user *lnbits.User
|
||||
var err error
|
||||
if user, err = getCachedUser(u, bot); err != nil {
|
||||
user, err = GetLnbitsUser(u, bot)
|
||||
if err != nil {
|
||||
return user, err
|
||||
}
|
||||
updateCachedUser(user, bot)
|
||||
}
|
||||
if telegramUserChanged(u, user.Telegram) {
|
||||
// update possibly changed user details in Database
|
||||
user.Telegram = u
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
log.Warnln(fmt.Sprintf("[UpdateUserRecord] %s", err.Error()))
|
||||
}
|
||||
}
|
||||
return user, err
|
||||
}
|
||||
|
||||
func updateCachedUser(apiUser *lnbits.User, bot TipBot) {
|
||||
bot.Cache.Set(apiUser.Name, apiUser, &store.Options{Expiration: 1 * time.Minute})
|
||||
}
|
||||
|
||||
func telegramUserChanged(apiUser, stateUser *tb.User) bool {
|
||||
if reflect.DeepEqual(apiUser, stateUser) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
func 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))
|
||||
if bot.Cache.GoCacheStore != nil {
|
||||
updateCachedUser(user, bot)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"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"
|
||||
)
|
||||
|
||||
// PLEASE DO NOT CHANGE THE CODE IN THIS FILE
|
||||
// YOU MIGHT BREAK DONATIONS TO THE ORIGINAL PROJECT
|
||||
// THE DEVELOPMENT OF LIGHTNINGTIPBOT RELIES ON DONATIONS
|
||||
// IF YOU USE THIS PROJECT, LEAVE THIS CODE ALONE
|
||||
|
||||
var (
|
||||
donationEndpoint string
|
||||
)
|
||||
|
||||
func helpDonateUsage(ctx context.Context, errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(Translate(ctx, "donateHelpText"), fmt.Sprintf("%s", errormsg))
|
||||
} else {
|
||||
return fmt.Sprintf(Translate(ctx, "donateHelpText"), "")
|
||||
}
|
||||
}
|
||||
|
||||
func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
// if no amount is in the command, ask for it
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
|
||||
// // no amount was entered, set user state and ask for amount
|
||||
_, err = bot.askForAmount(ctx, "", "CreateDonationState", 0, 0, m.Text)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// command is valid
|
||||
msg := bot.trySendMessageEditable(m.Chat, Translate(ctx, "donationProgressMessage"))
|
||||
// get invoice
|
||||
resp, err := http.Get(fmt.Sprintf(donationEndpoint, amount, GetUserStr(user.Telegram), GetUserStr(bot.Telegram.Me)))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// send donation invoice
|
||||
// user := LoadUser(ctx)
|
||||
// bot.trySendMessage(user.Telegram, string(body))
|
||||
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: string(body)}, bot.Client)
|
||||
if err != nil {
|
||||
userStr := GetUserStr(user.Telegram)
|
||||
errmsg := fmt.Sprintf("[/donate] Donation failed for user %s: %s", userStr, err)
|
||||
log.Errorln(errmsg)
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
// hotfix because the edit doesn't work!
|
||||
// todo: fix edit
|
||||
// bot.tryEditMessage(msg, Translate(ctx, "donationSuccess"))
|
||||
bot.tryDeleteMessage(msg)
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "donationSuccess"))
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
var sb strings.Builder
|
||||
_, err := io.Copy(&sb, rot13Reader{strings.NewReader("uggcf://ya.gvcf/qbangr/%q?sebz=%f&obg=%f")})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
donationEndpoint = sb.String()
|
||||
}
|
||||
|
||||
type rot13Reader struct {
|
||||
r io.Reader
|
||||
}
|
||||
|
||||
func (rot13 rot13Reader) Read(b []byte) (int, error) {
|
||||
n, err := rot13.r.Read(b)
|
||||
for i := 0; i < n; i++ {
|
||||
switch {
|
||||
case b[i] >= 65 && b[i] <= 90:
|
||||
if b[i] <= 77 {
|
||||
b[i] = b[i] + 13
|
||||
} else {
|
||||
b[i] = b[i] - 13
|
||||
}
|
||||
case b[i] >= 97 && b[i] <= 122:
|
||||
if b[i] <= 109 {
|
||||
b[i] = b[i] + 13
|
||||
} else {
|
||||
b[i] = b[i] - 13
|
||||
}
|
||||
}
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (bot TipBot) parseCmdDonHandler(ctx context.Context, m *tb.Message) error {
|
||||
arg := ""
|
||||
if strings.HasPrefix(strings.ToLower(m.Text), "/send") {
|
||||
arg, _ = getArgumentFromCommand(m.Text, 2)
|
||||
if arg != "@"+bot.Telegram.Me.Username {
|
||||
return fmt.Errorf("err")
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(strings.ToLower(m.Text), "/tip") {
|
||||
arg = GetUserStr(m.ReplyTo.Sender)
|
||||
if arg != "@"+bot.Telegram.Me.Username {
|
||||
return fmt.Errorf("err")
|
||||
}
|
||||
}
|
||||
if arg == "@LightningTipBot" || len(arg) < 1 {
|
||||
return fmt.Errorf("err")
|
||||
}
|
||||
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
_, err = io.Copy(&sb, rot13Reader{strings.NewReader("Gunax lbh! V'z ebhgvat guvf qbangvba gb YvtugavatGvcObg@ya.gvcf.")})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
donationInterceptMessage := sb.String()
|
||||
|
||||
bot.trySendMessage(m.Sender, str.MarkdownEscape(donationInterceptMessage))
|
||||
m.Text = fmt.Sprintf("/donate %d", amount)
|
||||
bot.donationHandler(ctx, m)
|
||||
// returning nil here will abort the parent handler (/pay or /tip)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
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()))
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
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"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
inlineFaucetMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelInlineFaucet = inlineFaucetMenu.Data("🚫 Cancel", "cancel_faucet_inline")
|
||||
btnAcceptInlineFaucet = inlineFaucetMenu.Data("✅ Collect", "confirm_faucet_inline")
|
||||
)
|
||||
|
||||
type InlineFaucet struct {
|
||||
*storage.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"`
|
||||
From *lnbits.User `json:"inline_faucet_from"`
|
||||
To []*lnbits.User `json:"inline_faucet_to"`
|
||||
Memo string `json:"inline_faucet_memo"`
|
||||
NTotal int `json:"inline_faucet_ntotal"`
|
||||
NTaken int `json:"inline_faucet_ntaken"`
|
||||
UserNeedsWallet bool `json:"inline_faucet_userneedswallet"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
}
|
||||
|
||||
func (bot TipBot) mapFaucetLanguage(ctx context.Context, command string) context.Context {
|
||||
if len(strings.Split(command, " ")) > 1 {
|
||||
c := strings.Split(command, " ")[0][1:] // cut the /
|
||||
ctx = bot.commandTranslationMap(ctx, c)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User) (*InlineFaucet, error) {
|
||||
amount, err := decodeAmountFromCommand(text)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.DecodeAmountError, err)
|
||||
}
|
||||
peruserStr, err := getArgumentFromCommand(text, 2)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.DecodePerUserAmountError, err)
|
||||
}
|
||||
perUserAmount, err := getAmount(peruserStr)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.InvalidAmountError, err)
|
||||
}
|
||||
if perUserAmount < 5 || amount%perUserAmount != 0 {
|
||||
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("invalid amount per user"))
|
||||
}
|
||||
nTotal := int(amount / perUserAmount)
|
||||
fromUser := LoadUser(ctx)
|
||||
fromUserStr := GetUserStr(sender)
|
||||
balance, err := bot.GetUserBalanceCached(fromUser)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.GetBalanceError, err)
|
||||
}
|
||||
// check if fromUser has balance
|
||||
if balance < amount {
|
||||
return nil, errors.New(errors.BalanceToLowError, fmt.Errorf("[faucet] Balance of user %s too low", fromUserStr))
|
||||
}
|
||||
// // 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))
|
||||
if len(memo) > 0 {
|
||||
inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineFaucetAppendMemo"), memo)
|
||||
}
|
||||
id := fmt.Sprintf("faucet:%s:%d", RandStringRunes(10), amount)
|
||||
|
||||
return &InlineFaucet{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Message: inlineMessage,
|
||||
Amount: amount,
|
||||
From: fromUser,
|
||||
Memo: memo,
|
||||
PerUserAmount: perUserAmount,
|
||||
NTotal: nTotal,
|
||||
NTaken: 0,
|
||||
RemainingAmount: amount,
|
||||
UserNeedsWallet: false,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}, nil
|
||||
|
||||
}
|
||||
func (bot TipBot) makeFaucet(ctx context.Context, m *tb.Message, query bool) (*InlineFaucet, error) {
|
||||
faucet, err := bot.createFaucet(ctx, m.Text, m.Sender)
|
||||
if err != nil {
|
||||
switch err.(errors.TipBotError).Code {
|
||||
case errors.DecodeAmountError:
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.DecodePerUserAmountError:
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), ""))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.InvalidAmountError:
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.InvalidAmountPerUserError:
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidPeruserAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.GetBalanceError:
|
||||
// log.Errorln(err.Error())
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.BalanceToLowError:
|
||||
// log.Errorf(err.Error())
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "inlineSendBalanceLowMessage"))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return faucet, err
|
||||
}
|
||||
|
||||
func (bot TipBot) makeQueryFaucet(ctx context.Context, q *tb.Query, query bool) (*InlineFaucet, error) {
|
||||
faucet, err := bot.createFaucet(ctx, q.Text, &q.From)
|
||||
if err != nil {
|
||||
switch err.(errors.TipBotError).Code {
|
||||
case errors.DecodeAmountError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.DecodePerUserAmountError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.InvalidAmountError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.InvalidAmountPerUserError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineFaucetInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.GetBalanceError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.BalanceToLowError:
|
||||
log.Errorf(err.Error())
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return faucet, err
|
||||
}
|
||||
|
||||
func (bot TipBot) makeFaucetKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
|
||||
inlineFaucetMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
acceptInlineFaucetButton := inlineFaucetMenu.Data(Translate(ctx, "collectButtonMessage"), "confirm_faucet_inline", id)
|
||||
cancelInlineFaucetButton := inlineFaucetMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_faucet_inline", id)
|
||||
inlineFaucetMenu.Inline(
|
||||
inlineFaucetMenu.Row(
|
||||
acceptInlineFaucetButton,
|
||||
cancelInlineFaucetButton),
|
||||
)
|
||||
return inlineFaucetMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) faucetHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if m.Private() {
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetHelpFaucetInGroup")))
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
ctx = bot.mapFaucetLanguage(ctx, m.Text)
|
||||
inlineFaucet, err := bot.makeFaucet(ctx, m, false)
|
||||
if err != nil {
|
||||
log.Warnf("[faucet] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
fromUserStr := GetUserStr(m.Sender)
|
||||
mFaucet := bot.trySendMessage(m.Chat, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
|
||||
log.Infof("[faucet] %s created faucet %s: %d sat (%d per user)", fromUserStr, inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) (context.Context, error) {
|
||||
inlineFaucet, err := bot.makeQueryFaucet(ctx, q, false)
|
||||
if err != nil {
|
||||
log.Errorf("[handleInlineFaucetQuery] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
urls := []string{
|
||||
queryImage,
|
||||
}
|
||||
results := make(tb.Results, len(urls)) // []tb.Result
|
||||
for i, url := range urls {
|
||||
result := &tb.ArticleResult{
|
||||
// URL: url,
|
||||
Text: inlineFaucet.Message,
|
||||
Title: fmt.Sprintf(TranslateUser(ctx, "inlineResultFaucetTitle"), inlineFaucet.Amount),
|
||||
Description: TranslateUser(ctx, "inlineResultFaucetDescription"),
|
||||
// required for photos
|
||||
ThumbURL: url,
|
||||
}
|
||||
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeFaucetKeyboard(ctx, inlineFaucet.ID).InlineKeyboard}
|
||||
results[i] = result
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(inlineFaucet.ID)
|
||||
|
||||
bot.Cache.Set(inlineFaucet.ID, inlineFaucet, &store.Options{Expiration: 5 * time.Minute})
|
||||
log.Infof("[faucet] %s:%d created inline faucet %s: %d sat (%d per user)", GetUserStr(inlineFaucet.From.Telegram), inlineFaucet.From.Telegram.ID, inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
|
||||
}
|
||||
|
||||
err = bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
Results: results,
|
||||
CacheTime: 1,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
|
||||
to := LoadUser(ctx)
|
||||
tx := &InlineFaucet{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptInlineFaucetHandler] c.Data: %s, Error: %s", c.Data, err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
log.Tracef("[acceptInlineFaucetHandler] Callback c.Data: %s tx.ID: %s", c.Data, tx.ID)
|
||||
|
||||
inlineFaucet := fn.(*InlineFaucet)
|
||||
from := inlineFaucet.From
|
||||
// failsafe for queued users
|
||||
if !inlineFaucet.Active {
|
||||
log.Tracef(fmt.Sprintf("[faucet] faucet %s inactive. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
|
||||
bot.finishFaucet(ctx, c, inlineFaucet)
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
// log faucet link if possible
|
||||
if c.Message != nil && c.Message.Chat != nil {
|
||||
log.Infof("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(c.Message.Chat.ID, 10)[4:], c.Message.ID)
|
||||
}
|
||||
|
||||
if 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)
|
||||
}
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
defer inlineFaucet.Set(inlineFaucet, bot.Bunt)
|
||||
|
||||
if inlineFaucet.RemainingAmount >= inlineFaucet.PerUserAmount {
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
// check if user exists and create a wallet if not
|
||||
_, exists := bot.UserExists(to.Telegram)
|
||||
if !exists {
|
||||
to, err = bot.CreateWalletForTelegramUser(to.Telegram)
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[faucet] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
|
||||
if !to.Initialized {
|
||||
inlineFaucet.UserNeedsWallet = true
|
||||
}
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("Faucet from %s to %s (%d sat).", fromUserStr, toUserStr, inlineFaucet.PerUserAmount)
|
||||
t := NewTransaction(bot, from, to, inlineFaucet.PerUserAmount, TransactionType("faucet"))
|
||||
t.Memo = transactionMemo
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
log.Infof("[💸 faucet] Faucet %s from %s to %s:%d (%d sat).", inlineFaucet.ID, fromUserStr, toUserStr, to.Telegram.ID, inlineFaucet.PerUserAmount)
|
||||
inlineFaucet.NTaken += 1
|
||||
inlineFaucet.To = append(inlineFaucet.To, to)
|
||||
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))
|
||||
}()
|
||||
|
||||
// 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))
|
||||
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))
|
||||
}
|
||||
// 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))
|
||||
}
|
||||
|
||||
}
|
||||
if inlineFaucet.RemainingAmount < inlineFaucet.PerUserAmount {
|
||||
log.Debugf(fmt.Sprintf("[faucet] faucet %s empty. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
|
||||
// faucet is depleted
|
||||
bot.finishFaucet(ctx, c, inlineFaucet)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineFaucet(ctx context.Context, c *tb.Callback, ignoreID bool) (context.Context, error) {
|
||||
tx := &InlineFaucet{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Debugf("[cancelInlineFaucetHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
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)
|
||||
// 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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
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)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,86 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot TipBot) makeHelpMessage(ctx context.Context, m *tb.Message) string {
|
||||
fromUser := LoadUser(ctx)
|
||||
dynamicHelpMessage := ""
|
||||
// user has no username set
|
||||
if len(m.Sender.Username) == 0 {
|
||||
// return fmt.Sprintf(helpMessage, fmt.Sprintf("%s\n\n", helpNoUsernameMessage))
|
||||
dynamicHelpMessage = dynamicHelpMessage + "\n" + Translate(ctx, "helpNoUsernameMessage")
|
||||
}
|
||||
lnaddr, _ := bot.UserGetLightningAddress(fromUser)
|
||||
if len(lnaddr) > 0 {
|
||||
dynamicHelpMessage = dynamicHelpMessage + "\n" + fmt.Sprintf(Translate(ctx, "infoYourLightningAddress"), lnaddr)
|
||||
}
|
||||
if len(dynamicHelpMessage) > 0 {
|
||||
dynamicHelpMessage = Translate(ctx, "infoHelpMessage") + dynamicHelpMessage
|
||||
}
|
||||
helpMessage := Translate(ctx, "helpMessage")
|
||||
return fmt.Sprintf(helpMessage, dynamicHelpMessage)
|
||||
}
|
||||
|
||||
func (bot TipBot) helpHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if !m.Private() {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
bot.trySendMessage(m.Sender, bot.makeHelpMessage(ctx, m), tb.NoPreview)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot TipBot) basicsHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if !m.Private() {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "basicsMessage"), tb.NoPreview)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot TipBot) makeAdvancedHelpMessage(ctx context.Context, m *tb.Message) string {
|
||||
fromUser := LoadUser(ctx)
|
||||
dynamicHelpMessage := "ℹ️ *Info*\n"
|
||||
// user has no username set
|
||||
if len(m.Sender.Username) == 0 {
|
||||
// return fmt.Sprintf(helpMessage, fmt.Sprintf("%s\n\n", helpNoUsernameMessage))
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("%s", Translate(ctx, "helpNoUsernameMessage")) + "\n"
|
||||
}
|
||||
// we print the anonymous ln address in the advanced help
|
||||
lnaddr, err := bot.UserGetAnonLightningAddress(fromUser)
|
||||
if err == nil {
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Anonymous lightning address: `%s`\n", lnaddr)
|
||||
}
|
||||
lnurl, err := UserGetLNURL(fromUser)
|
||||
if err == nil {
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("LNURL: `%s`", lnurl)
|
||||
}
|
||||
|
||||
// this is so stupid:
|
||||
return fmt.Sprintf(
|
||||
Translate(ctx, "advancedMessage"),
|
||||
dynamicHelpMessage,
|
||||
GetUserStr(bot.Telegram.Me),
|
||||
)
|
||||
}
|
||||
|
||||
func (bot TipBot) advancedHelpHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if !m.Private() {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
bot.trySendMessage(m.Sender, bot.makeAdvancedHelpMessage(ctx, m), tb.NoPreview)
|
||||
return ctx, nil
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"math"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
}
|
||||
|
||||
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
||||
|
||||
func RandStringRunes(n int) string {
|
||||
b := make([]rune, n)
|
||||
for i := range b {
|
||||
b[i] = letterRunes[rand.Intn(len(letterRunes))]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func GetMemoFromCommand(command string, fromWord int) string {
|
||||
// check for memo in command
|
||||
memo := ""
|
||||
if len(strings.Split(command, " ")) > fromWord {
|
||||
memo = strings.SplitN(command, " ", fromWord+1)[fromWord]
|
||||
memoMaxLen := 159
|
||||
if len(memo) > memoMaxLen {
|
||||
memo = memo[:memoMaxLen]
|
||||
}
|
||||
}
|
||||
return memo
|
||||
}
|
||||
|
||||
func MakeProgressbar(current int64, total int64) string {
|
||||
MAX_BARS := 16
|
||||
progress := math.Round((float64(current) / float64(total)) * float64(MAX_BARS))
|
||||
progressbar := strings.Repeat("🟩", int(progress))
|
||||
progressbar += strings.Repeat("⬜️", MAX_BARS-int(progress))
|
||||
return progressbar
|
||||
}
|
||||
|
||||
func MakeTipjarbar(current int64, total int64) string {
|
||||
MAX_BARS := 16
|
||||
progress := math.Round((float64(current) / float64(total)) * float64(MAX_BARS))
|
||||
progressbar := strings.Repeat("🍯", int(progress))
|
||||
progressbar += strings.Repeat("⬜️", MAX_BARS-int(progress))
|
||||
return progressbar
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
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"
|
||||
)
|
||||
|
||||
const queryImage = "https://avatars.githubusercontent.com/u/88730856?v=4"
|
||||
|
||||
func (bot TipBot) inlineQueryInstructions(ctx context.Context, q *tb.Query) (context.Context, error) {
|
||||
instructions := []struct {
|
||||
url string
|
||||
title string
|
||||
description string
|
||||
}{
|
||||
{
|
||||
url: queryImage,
|
||||
title: TranslateUser(ctx, "inlineQuerySendTitle"),
|
||||
description: fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username),
|
||||
},
|
||||
{
|
||||
url: queryImage,
|
||||
title: TranslateUser(ctx, "inlineQueryReceiveTitle"),
|
||||
description: fmt.Sprintf(TranslateUser(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username),
|
||||
},
|
||||
{
|
||||
url: queryImage,
|
||||
title: TranslateUser(ctx, "inlineQueryFaucetTitle"),
|
||||
description: fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username),
|
||||
},
|
||||
{
|
||||
url: queryImage,
|
||||
title: TranslateUser(ctx, "inlineQueryTipjarTitle"),
|
||||
description: fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username),
|
||||
},
|
||||
}
|
||||
results := make(tb.Results, len(instructions)) // []tb.Result
|
||||
for i, instruction := range instructions {
|
||||
result := &tb.ArticleResult{
|
||||
//URL: instruction.url,
|
||||
Text: instruction.description,
|
||||
Title: instruction.title,
|
||||
Description: instruction.description,
|
||||
// required for photos
|
||||
ThumbURL: instruction.url,
|
||||
}
|
||||
results[i] = result
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(strconv.Itoa(i))
|
||||
}
|
||||
|
||||
err := bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
Results: results,
|
||||
CacheTime: 5, // a minute
|
||||
IsPersonal: true,
|
||||
QueryID: q.ID,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
func (bot TipBot) inlineQueryReplyWithError(q *tb.Query, message string, help string) {
|
||||
results := make(tb.Results, 1) // []tb.Result
|
||||
result := &tb.ArticleResult{
|
||||
// URL: url,
|
||||
Text: help,
|
||||
Title: message,
|
||||
Description: help,
|
||||
// required for photos
|
||||
ThumbURL: queryImage,
|
||||
}
|
||||
id := fmt.Sprintf("inl-error-%d-%s", q.From.ID, RandStringRunes(5))
|
||||
result.SetResultID(id)
|
||||
results[0] = result
|
||||
err := bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
Results: results,
|
||||
CacheTime: 1, // 60 == 1 minute, todo: make higher than 1 s in production
|
||||
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
func (bot TipBot) commandTranslationMap(ctx context.Context, command string) context.Context {
|
||||
switch command {
|
||||
// is default, we don't have to check it
|
||||
// case "faucet":
|
||||
// ctx = context.WithValue(ctx, "publicLanguageCode", "en")
|
||||
// ctx = context.WithValue(ctx, "publicLocalizer", i18n.NewLocalizer(i18n.Bundle, "en"))
|
||||
case "zapfhahn", "spendendose":
|
||||
ctx = context.WithValue(ctx, "publicLanguageCode", "de")
|
||||
ctx = context.WithValue(ctx, "publicLocalizer", i18n2.NewLocalizer(i18n.Bundle, "de"))
|
||||
case "kraan":
|
||||
ctx = context.WithValue(ctx, "publicLanguageCode", "nl")
|
||||
ctx = context.WithValue(ctx, "publicLocalizer", i18n2.NewLocalizer(i18n.Bundle, "nl"))
|
||||
case "grifo":
|
||||
ctx = context.WithValue(ctx, "publicLanguageCode", "es")
|
||||
ctx = context.WithValue(ctx, "publicLocalizer", i18n2.NewLocalizer(i18n.Bundle, "es"))
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (bot TipBot) anyQueryHandler(ctx context.Context, q *tb.Query) (context.Context, error) {
|
||||
if q.Text == "" {
|
||||
return bot.inlineQueryInstructions(ctx, q)
|
||||
}
|
||||
|
||||
// create the inline send result
|
||||
if strings.HasPrefix(q.Text, "/") {
|
||||
q.Text = strings.TrimPrefix(q.Text, "/")
|
||||
}
|
||||
if strings.HasPrefix(q.Text, "send") || strings.HasPrefix(q.Text, "pay") {
|
||||
return bot.handleInlineSendQuery(ctx, q)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(q.Text, "faucet") || strings.HasPrefix(q.Text, "zapfhahn") || strings.HasPrefix(q.Text, "kraan") || strings.HasPrefix(q.Text, "grifo") {
|
||||
if len(strings.Split(q.Text, " ")) > 1 {
|
||||
c := strings.Split(q.Text, " ")[0]
|
||||
ctx = bot.commandTranslationMap(ctx, c)
|
||||
}
|
||||
return bot.handleInlineFaucetQuery(ctx, q)
|
||||
}
|
||||
if strings.HasPrefix(q.Text, "tipjar") || strings.HasPrefix(q.Text, "spendendose") {
|
||||
if len(strings.Split(q.Text, " ")) > 1 {
|
||||
c := strings.Split(q.Text, " ")[0]
|
||||
ctx = bot.commandTranslationMap(ctx, c)
|
||||
}
|
||||
return bot.handleInlineTipjarQuery(ctx, q)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(q.Text, "receive") || strings.HasPrefix(q.Text, "get") || strings.HasPrefix(q.Text, "payme") || strings.HasPrefix(q.Text, "request") {
|
||||
return bot.handleInlineReceiveQuery(ctx, q)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
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/runtime"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
inlineReceiveMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelInlineReceive = inlineReceiveMenu.Data("🚫 Cancel", "cancel_receive_inline")
|
||||
btnAcceptInlineReceive = inlineReceiveMenu.Data("💸 Pay", "confirm_receive_inline")
|
||||
)
|
||||
|
||||
type InlineReceive struct {
|
||||
*storage.Base
|
||||
MessageText string `json:"inline_receive_messagetext"`
|
||||
Message *tb.Message `json:"inline_receive_message"`
|
||||
Amount int64 `json:"inline_receive_amount"`
|
||||
From *lnbits.User `json:"inline_receive_from"`
|
||||
To *lnbits.User `json:"inline_receive_to"`
|
||||
From_SpecificUser bool `json:"from_specific_user"`
|
||||
Memo string `json:"inline_receive_memo"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
}
|
||||
|
||||
func (bot TipBot) makeReceiveKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
|
||||
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,
|
||||
),
|
||||
)
|
||||
return inlineReceiveMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) (context.Context, error) {
|
||||
to := LoadUser(ctx)
|
||||
amount, err := decodeAmountFromCommand(q.Text)
|
||||
if err != nil {
|
||||
bot.inlineQueryReplyWithError(q, Translate(ctx, "inlineQueryReceiveTitle"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, err
|
||||
}
|
||||
if amount < 1 {
|
||||
bot.inlineQueryReplyWithError(q, Translate(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
}
|
||||
toUserStr := GetUserStr(&q.From)
|
||||
|
||||
// check whether the 3rd argument is a username
|
||||
// command is "@LightningTipBot receive 123 @from_user This is the memo"
|
||||
memo_argn := 2 // argument index at which the memo starts, will be 3 if there is a from_username in command
|
||||
fromUserDb := &lnbits.User{}
|
||||
from_SpecificUser := false
|
||||
if len(strings.Split(q.Text, " ")) > 2 {
|
||||
from_username := strings.Split(q.Text, " ")[2]
|
||||
if strings.HasPrefix(from_username, "@") {
|
||||
fromUserDb, err = GetUserByTelegramUsername(from_username[1:], bot) // must be without the @
|
||||
if err != nil {
|
||||
//bot.tryDeleteMessage(m)
|
||||
//bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), toUserStrMention))
|
||||
bot.inlineQueryReplyWithError(q,
|
||||
fmt.Sprintf(TranslateUser(ctx, "sendUserHasNoWalletMessage"), from_username),
|
||||
fmt.Sprintf(TranslateUser(ctx, "inlineQueryReceiveDescription"),
|
||||
bot.Telegram.Me.Username))
|
||||
return ctx, err
|
||||
}
|
||||
memo_argn = 3 // assume that memo starts after the from_username
|
||||
from_SpecificUser = true
|
||||
}
|
||||
}
|
||||
|
||||
// check for memo in command
|
||||
memo := GetMemoFromCommand(q.Text, memo_argn)
|
||||
urls := []string{
|
||||
queryImage,
|
||||
}
|
||||
results := make(tb.Results, len(urls)) // []tb.Result
|
||||
for i, url := range urls {
|
||||
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineReceiveMessage"), toUserStr, amount)
|
||||
|
||||
// modify message if payment is to specific user
|
||||
if from_SpecificUser {
|
||||
inlineMessage = fmt.Sprintf("@%s: %s", fromUserDb.Telegram.Username, inlineMessage)
|
||||
}
|
||||
|
||||
if len(memo) > 0 {
|
||||
inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineReceiveAppendMemo"), memo)
|
||||
}
|
||||
result := &tb.ArticleResult{
|
||||
// URL: url,
|
||||
Text: inlineMessage,
|
||||
Title: fmt.Sprintf(TranslateUser(ctx, "inlineResultReceiveTitle"), amount),
|
||||
Description: fmt.Sprintf(TranslateUser(ctx, "inlineResultReceiveDescription"), amount),
|
||||
// required for photos
|
||||
ThumbURL: url,
|
||||
}
|
||||
id := fmt.Sprintf("inl-receive-%d-%d-%s", q.From.ID, amount, RandStringRunes(5))
|
||||
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeReceiveKeyboard(ctx, id).InlineKeyboard}
|
||||
results[i] = result
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(id)
|
||||
// create persistend inline send struct
|
||||
inlineReceive := InlineReceive{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
MessageText: inlineMessage,
|
||||
To: to,
|
||||
Memo: memo,
|
||||
Amount: amount,
|
||||
From: fromUserDb,
|
||||
From_SpecificUser: from_SpecificUser,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
bot.Cache.Set(inlineReceive.ID, inlineReceive, &store.Options{Expiration: 5 * time.Minute})
|
||||
}
|
||||
|
||||
err = bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
Results: results,
|
||||
CacheTime: 1, // 60 == 1 minute, todo: make higher than 1 s in production
|
||||
|
||||
})
|
||||
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)
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
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)
|
||||
}
|
||||
|
||||
// user `from` is the one who is SENDING
|
||||
// user `to` is the one who is RECEIVING
|
||||
from := LoadUser(ctx)
|
||||
// check if this payment is requested from a specific user
|
||||
if inlineReceive.From_SpecificUser {
|
||||
if inlineReceive.From.Telegram.ID != from.Telegram.ID {
|
||||
// log.Infof("User %d is not User %d", inlineReceive.From.Telegram.ID, from.Telegram.ID)
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
} 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
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
// 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
|
||||
}
|
||||
// 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)
|
||||
}
|
||||
|
||||
// set inactive to avoid double-sends
|
||||
inlineReceive.Inactivate(inlineReceive, bot.Bunt)
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("InlineReceive from %s to %s (%d sat).", fromUserStr, toUserStr, inlineReceive.Amount)
|
||||
t := NewTransaction(bot, from, to, inlineReceive.Amount, TransactionType("inline receive"))
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
errMsg := fmt.Sprintf("[acceptInlineReceiveHandler] Transaction failed: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveFailedMessage"), &tb.ReplyMarkup{})
|
||||
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
|
||||
}
|
||||
|
||||
// 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))
|
||||
memo := inlineReceive.Memo
|
||||
if len(memo) > 0 {
|
||||
inlineReceive.MessageText += 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))
|
||||
}
|
||||
|
||||
bot.tryEditMessage(inlineReceive.Message, inlineReceive.MessageText, &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))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[acceptInlineReceiveHandler] Error: Receive message to %s: %s", toUserStr, err)
|
||||
log.Warnln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
// inlineReceive.Release(inlineReceive, bot.Bunt)
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineReceiveHandler(ctx context.Context, c *tb.Callback) (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
|
||||
rn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineReceiveHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
if c.Sender.ID != inlineReceive.To.Telegram.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineReceive inactive
|
||||
inlineReceive.Active = false
|
||||
return ctx, inlineReceive.Set(inlineReceive, bot.Bunt)
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
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"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
inlineSendMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelInlineSend = inlineSendMenu.Data("🚫 Cancel", "cancel_send_inline")
|
||||
btnAcceptInlineSend = inlineSendMenu.Data("✅ Receive", "confirm_send_inline")
|
||||
)
|
||||
|
||||
type InlineSend struct {
|
||||
*storage.Base
|
||||
Message string `json:"inline_send_message"`
|
||||
Amount int64 `json:"inline_send_amount"`
|
||||
From *lnbits.User `json:"inline_send_from"`
|
||||
To *lnbits.User `json:"inline_send_to"`
|
||||
To_SpecificUser bool `json:"to_specific_user"`
|
||||
Memo string `json:"inline_send_memo"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
}
|
||||
|
||||
func (bot TipBot) makeSendKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
|
||||
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
|
||||
cancelInlineSendButton.Data = id
|
||||
|
||||
inlineSendMenu.Inline(
|
||||
inlineSendMenu.Row(
|
||||
acceptInlineSendButton,
|
||||
cancelInlineSendButton),
|
||||
)
|
||||
return inlineSendMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineSendQuery(ctx context.Context, q *tb.Query) (context.Context, error) {
|
||||
// inlineSend := NewInlineSend()
|
||||
// var err error
|
||||
amount, err := decodeAmountFromCommand(q.Text)
|
||||
if err != nil {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQuerySendTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, err
|
||||
}
|
||||
if amount < 1 {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
}
|
||||
fromUser := LoadUser(ctx)
|
||||
fromUserStr := GetUserStr(&q.From)
|
||||
balance, err := bot.GetUserBalanceCached(fromUser)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
// check if fromUser has balance
|
||||
if balance < amount {
|
||||
log.Errorf("Balance of user %s too low", fromUserStr)
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
}
|
||||
|
||||
// check whether the 3rd argument is a username
|
||||
// command is "@LightningTipBot send 123 @to_user This is the memo"
|
||||
memo_argn := 2 // argument index at which the memo starts, will be 3 if there is a to_username in command
|
||||
toUserDb := &lnbits.User{}
|
||||
to_SpecificUser := false
|
||||
if len(strings.Split(q.Text, " ")) > 2 {
|
||||
to_username := strings.Split(q.Text, " ")[2]
|
||||
if strings.HasPrefix(to_username, "@") {
|
||||
toUserDb, err = GetUserByTelegramUsername(to_username[1:], bot) // must be without the @
|
||||
if err != nil {
|
||||
//bot.tryDeleteMessage(m)
|
||||
//bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), toUserStrMention))
|
||||
bot.inlineQueryReplyWithError(q,
|
||||
fmt.Sprintf(TranslateUser(ctx, "sendUserHasNoWalletMessage"), to_username),
|
||||
fmt.Sprintf(TranslateUser(ctx, "inlineQuerySendDescription"),
|
||||
bot.Telegram.Me.Username))
|
||||
return ctx, err
|
||||
}
|
||||
memo_argn = 3 // assume that memo starts after the to_username
|
||||
to_SpecificUser = true
|
||||
}
|
||||
}
|
||||
|
||||
// check for memo in command
|
||||
memo := GetMemoFromCommand(q.Text, memo_argn)
|
||||
urls := []string{
|
||||
queryImage,
|
||||
}
|
||||
results := make(tb.Results, len(urls)) // []tb.Result
|
||||
for i, url := range urls {
|
||||
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineSendMessage"), fromUserStr, amount)
|
||||
|
||||
// modify message if payment is to specific user
|
||||
if to_SpecificUser {
|
||||
inlineMessage = fmt.Sprintf("@%s: %s", toUserDb.Telegram.Username, inlineMessage)
|
||||
}
|
||||
|
||||
if len(memo) > 0 {
|
||||
inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineSendAppendMemo"), memo)
|
||||
}
|
||||
result := &tb.ArticleResult{
|
||||
// URL: url,
|
||||
Text: inlineMessage,
|
||||
Title: fmt.Sprintf(TranslateUser(ctx, "inlineResultSendTitle"), amount),
|
||||
Description: fmt.Sprintf(TranslateUser(ctx, "inlineResultSendDescription"), amount),
|
||||
// required for photos
|
||||
ThumbURL: url,
|
||||
}
|
||||
id := fmt.Sprintf("inl-send-%d-%d-%s", q.From.ID, amount, RandStringRunes(5))
|
||||
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeSendKeyboard(ctx, id).InlineKeyboard}
|
||||
results[i] = result
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(id)
|
||||
|
||||
// add data to persistent object
|
||||
inlineSend := InlineSend{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Message: inlineMessage,
|
||||
From: fromUser,
|
||||
To: toUserDb,
|
||||
To_SpecificUser: to_SpecificUser,
|
||||
Memo: memo,
|
||||
Amount: amount,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
|
||||
// add result to persistent struct
|
||||
bot.Cache.Set(inlineSend.ID, inlineSend, &store.Options{Expiration: 5 * time.Minute})
|
||||
}
|
||||
|
||||
err = bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
Results: results,
|
||||
CacheTime: 1, // 60 == 1 minute, todo: make higher than 1 s in production
|
||||
|
||||
})
|
||||
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) {
|
||||
to := LoadUser(ctx)
|
||||
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
// log.Errorf("[acceptInlineSendHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
inlineSend := sn.(*InlineSend)
|
||||
|
||||
fromUser := inlineSend.From
|
||||
if !inlineSend.Active {
|
||||
log.Errorf("[acceptInlineSendHandler] inline send not active anymore")
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
|
||||
defer inlineSend.Set(inlineSend, bot.Bunt)
|
||||
|
||||
amount := inlineSend.Amount
|
||||
|
||||
// check if this payment goes to a specific user
|
||||
if inlineSend.To_SpecificUser {
|
||||
if inlineSend.To.Telegram.ID != to.Telegram.ID {
|
||||
// log.Infof("User %d is not User %d", inlineSend.To.Telegram.ID, to.Telegram.ID)
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
} else {
|
||||
// otherwise, we just set it to the user who has clicked
|
||||
inlineSend.To = to
|
||||
}
|
||||
|
||||
if fromUser.Telegram.ID == to.Telegram.ID {
|
||||
bot.trySendMessage(fromUser.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(fromUser.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
fromUserStr := GetUserStr(fromUser.Telegram)
|
||||
|
||||
// check if user exists and create a wallet if not
|
||||
_, exists := bot.UserExists(to.Telegram)
|
||||
if !exists {
|
||||
log.Infof("[sendInline] User %s has no wallet.", toUserStr)
|
||||
to, err = bot.CreateWalletForTelegramUser(to.Telegram)
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[sendInline] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
// set inactive to avoid double-sends
|
||||
inlineSend.Inactivate(inlineSend, bot.Bunt)
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("InlineSend from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
t := NewTransaction(bot, fromUser, to, amount, TransactionType("inline send"))
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
errMsg := fmt.Sprintf("[sendInline] Transaction failed: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "inlineSendFailedMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
|
||||
log.Infof("[💸 sendInline] Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
|
||||
inlineSend.Message = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineSend.LanguageCode, "inlineSendUpdateMessageAccept"), amount, fromUserStrMd, toUserStrMd))
|
||||
memo := inlineSend.Memo
|
||||
if len(memo) > 0 {
|
||||
inlineSend.Message = inlineSend.Message + fmt.Sprintf(i18n.Translate(inlineSend.LanguageCode, "inlineSendAppendMemo"), memo)
|
||||
}
|
||||
if !to.Initialized {
|
||||
inlineSend.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineSend.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
bot.tryEditMessage(c.Message, inlineSend.Message, &tb.ReplyMarkup{})
|
||||
// notify users
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
|
||||
bot.trySendMessage(fromUser.Telegram, fmt.Sprintf(i18n.Translate(fromUser.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[sendInline] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineSendHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
|
||||
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineSendHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
inlineSend := sn.(*InlineSend)
|
||||
if c.Sender.ID != inlineSend.From.Telegram.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineSend inactive
|
||||
inlineSend.Active = false
|
||||
return ctx, inlineSend.Set(inlineSend, bot.Bunt)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type CallbackFuncHandler func(ctx context.Context, message *tb.Callback) (context.Context, error)
|
||||
type Func func(ctx context.Context, message interface{}) (context.Context, error)
|
||||
|
||||
type handlerCallbackInterceptor struct {
|
||||
handler CallbackFuncHandler
|
||||
before CallbackChain
|
||||
after CallbackChain
|
||||
onDefer CallbackChain
|
||||
}
|
||||
type CallbackChain []Func
|
||||
type CallbackInterceptOption func(*handlerCallbackInterceptor)
|
||||
|
||||
func WithBeforeCallback(chain ...Func) CallbackInterceptOption {
|
||||
return func(a *handlerCallbackInterceptor) {
|
||||
a.before = chain
|
||||
}
|
||||
}
|
||||
func WithAfterCallback(chain ...Func) CallbackInterceptOption {
|
||||
return func(a *handlerCallbackInterceptor) {
|
||||
a.after = chain
|
||||
}
|
||||
}
|
||||
func WithDeferCallback(chain ...Func) CallbackInterceptOption {
|
||||
return func(a *handlerCallbackInterceptor) {
|
||||
a.onDefer = chain
|
||||
}
|
||||
}
|
||||
|
||||
func interceptCallback(ctx context.Context, message *tb.Callback, hm CallbackChain) (context.Context, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if hm != nil {
|
||||
var err error
|
||||
for _, m := range hm {
|
||||
ctx, err = m(ctx, message)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func HandlerWithCallback(handler CallbackFuncHandler, option ...CallbackInterceptOption) func(Callback *tb.Callback) {
|
||||
hm := &handlerCallbackInterceptor{handler: handler}
|
||||
for _, opt := range option {
|
||||
opt(hm)
|
||||
}
|
||||
return func(c *tb.Callback) {
|
||||
ctx := context.Background()
|
||||
ctx, err := interceptCallback(ctx, c, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
defer interceptCallback(ctx, c, hm.onDefer)
|
||||
ctx, err = hm.handler(ctx, c)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
_, err = interceptCallback(ctx, c, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type MessageFuncHandler func(ctx context.Context, message *tb.Message) (context.Context, error)
|
||||
|
||||
type handlerMessageInterceptor struct {
|
||||
handler MessageFuncHandler
|
||||
before MessageChain
|
||||
after MessageChain
|
||||
onDefer MessageChain
|
||||
}
|
||||
type MessageChain []Func
|
||||
type MessageInterceptOption func(*handlerMessageInterceptor)
|
||||
|
||||
func WithBeforeMessage(chain ...Func) MessageInterceptOption {
|
||||
return func(a *handlerMessageInterceptor) {
|
||||
a.before = chain
|
||||
}
|
||||
}
|
||||
func WithAfterMessage(chain ...Func) MessageInterceptOption {
|
||||
return func(a *handlerMessageInterceptor) {
|
||||
a.after = chain
|
||||
}
|
||||
}
|
||||
func WithDeferMessage(chain ...Func) MessageInterceptOption {
|
||||
return func(a *handlerMessageInterceptor) {
|
||||
a.onDefer = chain
|
||||
}
|
||||
}
|
||||
|
||||
func interceptMessage(ctx context.Context, message *tb.Message, hm MessageChain) (context.Context, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if hm != nil {
|
||||
var err error
|
||||
for _, m := range hm {
|
||||
ctx, err = m(ctx, message)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func HandlerWithMessage(handler MessageFuncHandler, option ...MessageInterceptOption) func(message *tb.Message) {
|
||||
hm := &handlerMessageInterceptor{handler: handler}
|
||||
for _, opt := range option {
|
||||
opt(hm)
|
||||
}
|
||||
return func(message *tb.Message) {
|
||||
ctx := context.Background()
|
||||
ctx, err := interceptMessage(ctx, message, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
defer interceptMessage(ctx, message, hm.onDefer)
|
||||
ctx, err = hm.handler(ctx, message)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
_, err = interceptMessage(ctx, message, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type QueryFuncHandler func(ctx context.Context, message *tb.Query) (context.Context, error)
|
||||
|
||||
type handlerQueryInterceptor struct {
|
||||
handler QueryFuncHandler
|
||||
before QueryChain
|
||||
after QueryChain
|
||||
onDefer QueryChain
|
||||
}
|
||||
type QueryChain []Func
|
||||
type QueryInterceptOption func(*handlerQueryInterceptor)
|
||||
|
||||
func WithBeforeQuery(chain ...Func) QueryInterceptOption {
|
||||
return func(a *handlerQueryInterceptor) {
|
||||
a.before = chain
|
||||
}
|
||||
}
|
||||
func WithAfterQuery(chain ...Func) QueryInterceptOption {
|
||||
return func(a *handlerQueryInterceptor) {
|
||||
a.after = chain
|
||||
}
|
||||
}
|
||||
func WithDeferQuery(chain ...Func) QueryInterceptOption {
|
||||
return func(a *handlerQueryInterceptor) {
|
||||
a.onDefer = chain
|
||||
}
|
||||
}
|
||||
|
||||
func interceptQuery(ctx context.Context, message *tb.Query, hm QueryChain) (context.Context, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if hm != nil {
|
||||
var err error
|
||||
for _, m := range hm {
|
||||
ctx, err = m(ctx, message)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func HandlerWithQuery(handler QueryFuncHandler, option ...QueryInterceptOption) func(message *tb.Query) {
|
||||
hm := &handlerQueryInterceptor{handler: handler}
|
||||
for _, opt := range option {
|
||||
opt(hm)
|
||||
}
|
||||
return func(query *tb.Query) {
|
||||
ctx := context.Background()
|
||||
ctx, err := interceptQuery(context.Background(), query, hm.before)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
defer interceptQuery(ctx, query, hm.onDefer)
|
||||
ctx, err = hm.handler(ctx, query)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
_, err = interceptQuery(ctx, query, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
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"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type InterceptorType int
|
||||
|
||||
const (
|
||||
MessageInterceptor InterceptorType = iota
|
||||
CallbackInterceptor
|
||||
QueryInterceptor
|
||||
)
|
||||
|
||||
type Interceptor struct {
|
||||
Type InterceptorType
|
||||
Before []intercept.Func
|
||||
After []intercept.Func
|
||||
OnDefer []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
|
||||
case *tb.Callback:
|
||||
user = i.(*tb.Callback).Sender
|
||||
case *tb.Message:
|
||||
user = i.(*tb.Message).Sender
|
||||
default:
|
||||
log.Tracef("[getTelegramUserFromInterface] invalid type %s", reflect.TypeOf(i).String())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// loadReplyToInterceptor Loading the Telegram user with message intercept
|
||||
func (bot TipBot) loadReplyToInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
switch i.(type) {
|
||||
case *tb.Message:
|
||||
m := i.(*tb.Message)
|
||||
if m.ReplyTo != nil {
|
||||
if m.ReplyTo.Sender != nil {
|
||||
user, _ := GetUser(m.ReplyTo.Sender, bot)
|
||||
user.Telegram = m.ReplyTo.Sender
|
||||
return context.WithValue(ctx, "reply_to_user", user), nil
|
||||
}
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
return ctx, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
|
||||
func (bot TipBot) localizerInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
var userLocalizer *i18n2.Localizer
|
||||
var publicLocalizer *i18n2.Localizer
|
||||
|
||||
// default language is english
|
||||
publicLocalizer = i18n2.NewLocalizer(i18n.Bundle, "en")
|
||||
ctx = context.WithValue(ctx, "publicLanguageCode", "en")
|
||||
ctx = context.WithValue(ctx, "publicLocalizer", publicLocalizer)
|
||||
|
||||
switch i.(type) {
|
||||
case *tb.Message:
|
||||
m := i.(*tb.Message)
|
||||
userLocalizer = i18n2.NewLocalizer(i18n.Bundle, m.Sender.LanguageCode)
|
||||
ctx = context.WithValue(ctx, "userLanguageCode", m.Sender.LanguageCode)
|
||||
ctx = context.WithValue(ctx, "userLocalizer", userLocalizer)
|
||||
if m.Private() {
|
||||
// in pm overwrite public localizer with user localizer
|
||||
ctx = context.WithValue(ctx, "publicLanguageCode", m.Sender.LanguageCode)
|
||||
ctx = context.WithValue(ctx, "publicLocalizer", userLocalizer)
|
||||
}
|
||||
return ctx, nil
|
||||
case *tb.Callback:
|
||||
m := i.(*tb.Callback)
|
||||
userLocalizer = i18n2.NewLocalizer(i18n.Bundle, m.Sender.LanguageCode)
|
||||
ctx = context.WithValue(ctx, "userLanguageCode", m.Sender.LanguageCode)
|
||||
return context.WithValue(ctx, "userLocalizer", userLocalizer), nil
|
||||
case *tb.Query:
|
||||
m := i.(*tb.Query)
|
||||
userLocalizer = i18n2.NewLocalizer(i18n.Bundle, m.From.LanguageCode)
|
||||
ctx = context.WithValue(ctx, "userLanguageCode", m.From.LanguageCode)
|
||||
return context.WithValue(ctx, "userLocalizer", userLocalizer), nil
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot TipBot) requirePrivateChatInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
switch i.(type) {
|
||||
case *tb.Message:
|
||||
m := i.(*tb.Message)
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return nil, fmt.Errorf("[requirePrivateChatInterceptor] no private chat")
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
return nil, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
|
||||
const photoTag = "<Photo>"
|
||||
|
||||
func (bot TipBot) logMessageInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
switch i.(type) {
|
||||
case *tb.Message:
|
||||
m := i.(*tb.Message)
|
||||
if m.Text != "" {
|
||||
log_string := fmt.Sprintf("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
|
||||
if m.IsReply() {
|
||||
log_string = fmt.Sprintf("%s -> %s", log_string, GetUserStr(m.ReplyTo.Sender))
|
||||
}
|
||||
log.Infof(log_string)
|
||||
} else if m.Photo != nil {
|
||||
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, photoTag)
|
||||
}
|
||||
return ctx, nil
|
||||
case *tb.Callback:
|
||||
m := i.(*tb.Callback)
|
||||
log.Infof("[Callback %s:%d] Data: %s", GetUserStr(m.Sender), m.Sender.ID, m.Data)
|
||||
return ctx, nil
|
||||
}
|
||||
return nil, errors.Create(errors.InvalidTypeError)
|
||||
}
|
||||
|
||||
// LoadUser from context
|
||||
func LoadUserLocalizer(ctx context.Context) *i18n2.Localizer {
|
||||
u := ctx.Value("userLocalizer")
|
||||
if u != nil {
|
||||
return u.(*i18n2.Localizer)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadUser from context
|
||||
func LoadPublicLocalizer(ctx context.Context) *i18n2.Localizer {
|
||||
u := ctx.Value("publicLocalizer")
|
||||
if u != nil {
|
||||
return u.(*i18n2.Localizer)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadUser from context
|
||||
func LoadUser(ctx context.Context) *lnbits.User {
|
||||
u := ctx.Value("user")
|
||||
if u != nil {
|
||||
return u.(*lnbits.User)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadReplyToUser from context
|
||||
func LoadReplyToUser(ctx context.Context) *lnbits.User {
|
||||
u := ctx.Value("reply_to_user")
|
||||
if u != nil {
|
||||
return u.(*lnbits.User)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"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"
|
||||
)
|
||||
|
||||
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))
|
||||
} else {
|
||||
return fmt.Sprintf(Translate(ctx, "invoiceHelpText"), "")
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) invoiceHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
userStr := GetUserStr(user.Telegram)
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(m)
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
// if no amount is in the command, ask for it
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
|
||||
// // no amount was entered, set user state and ask fo""r amount
|
||||
_, err = bot.askForAmount(ctx, "", "CreateInvoiceState", 0, 0, m.Text)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// check for memo in command
|
||||
memo := "Powered by @LightningTipBot"
|
||||
if len(strings.Split(m.Text, " ")) > 2 {
|
||||
memo = GetMemoFromCommand(m.Text, 2)
|
||||
tag := " (@LightningTipBot)"
|
||||
memoMaxLen := 159 - len(tag)
|
||||
if len(memo) > memoMaxLen {
|
||||
memo = memo[:memoMaxLen-len(tag)]
|
||||
}
|
||||
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) {
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: int64(amount),
|
||||
Memo: memo,
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return InvoiceEvent{}, err
|
||||
}
|
||||
invoiceEvent := InvoiceEvent{
|
||||
Invoice: &Invoice{PaymentHash: invoice.PaymentHash,
|
||||
PaymentRequest: invoice.PaymentRequest,
|
||||
Amount: amount,
|
||||
Memo: memo},
|
||||
User: user,
|
||||
Callback: callback,
|
||||
CallbackData: callbackData,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
// save invoice struct for later use
|
||||
runtime.IgnoreError(bot.Bunt.Set(invoiceEvent))
|
||||
return invoiceEvent, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) notifyInvoiceReceivedEvent(invoiceEvent *InvoiceEvent) {
|
||||
// do balance check for keyboard update
|
||||
_, err := bot.GetUserBalance(invoiceEvent.User)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", GetUserStr(invoiceEvent.User.Telegram))
|
||||
log.Errorln(errmsg)
|
||||
}
|
||||
|
||||
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)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package telegram
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
func (bot *TipBot) lndhubHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
if internal.Configuration.Lnbits.LnbitsPublicUrl == "" {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "couldNotLinkMessage"))
|
||||
return ctx, fmt.Errorf("invalid configuration")
|
||||
}
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
// reply only in private message
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
// first check whether the user is initialized
|
||||
fromUser := LoadUser(ctx)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "walletConnectMessage"))
|
||||
|
||||
// do not respond to banned users
|
||||
if bot.UserIsBanned(fromUser) {
|
||||
log.Warnln("[lndhubHandler] user is banned. not responding.")
|
||||
return ctx, fmt.Errorf("user is banned")
|
||||
}
|
||||
|
||||
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())
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"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"
|
||||
|
||||
lnurl "github.com/fiatjaf/go-lnurl"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
// LnurlPayState saves the state of the user for an LNURL payment
|
||||
type LnurlPayState struct {
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
LNURLPayParams lnurl.LNURLPayParams `json:"LNURLPayParams"`
|
||||
LNURLPayValues lnurl.LNURLPayValues `json:"LNURLPayValues"`
|
||||
Amount int64 `json:"amount"`
|
||||
Comment string `json:"comment"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
}
|
||||
|
||||
// lnurlPayHandler1 is invoked when the first lnurl response was a lnurlpay response
|
||||
// at this point, the user hans't necessarily entered an amount yet
|
||||
func (bot *TipBot) lnurlPayHandler(ctx context.Context, m *tb.Message, payParams LnurlPayState) (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("lnurlp:%d:%s", m.Sender.ID, RandStringRunes(5))
|
||||
lnurlPayState := &LnurlPayState{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
From: user,
|
||||
LNURLPayParams: payParams.LNURLPayParams,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
|
||||
// first we check whether an amount is present in the command
|
||||
amount, amount_err := decodeAmountFromCommand(m.Text)
|
||||
|
||||
// we need to figure out whether the memo starts at position 2 or 3
|
||||
// so either /lnurl <amount> <lnurl> [memo] or /lnurl <lnurl> [memo]
|
||||
memoStartsAt := 2
|
||||
if amount_err == nil {
|
||||
// amount was present
|
||||
memoStartsAt = 3
|
||||
}
|
||||
// check if memo is present in command
|
||||
memo := GetMemoFromCommand(m.Text, memoStartsAt)
|
||||
// shorten memo to allowed length
|
||||
if len(memo) > int(lnurlPayState.LNURLPayParams.CommentAllowed) {
|
||||
memo = memo[:lnurlPayState.LNURLPayParams.CommentAllowed]
|
||||
}
|
||||
if len(memo) > 0 {
|
||||
lnurlPayState.Comment = memo
|
||||
}
|
||||
|
||||
// amount is already present in the command, i.e., /lnurl <amount> <LNURL>
|
||||
// amount not in allowed range from LNURL
|
||||
if amount_err == nil &&
|
||||
(int64(amount) > (lnurlPayState.LNURLPayParams.MaxSendable/1000) || int64(amount) < (lnurlPayState.LNURLPayParams.MinSendable/1000)) &&
|
||||
(lnurlPayState.LNURLPayParams.MaxSendable != 0 && lnurlPayState.LNURLPayParams.MinSendable != 0) { // only if max and min are set
|
||||
err := fmt.Errorf("amount not in range")
|
||||
log.Warnf("[lnurlPayHandler] Error: %s", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), lnurlPayState.LNURLPayParams.MinSendable/1000, lnurlPayState.LNURLPayParams.MaxSendable/1000))
|
||||
ResetUserState(user, bot)
|
||||
return 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
|
||||
paramsJson, err := json.Marshal(lnurlPayState)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandler] 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.lnurlPayHandlerSend(ctx, m)
|
||||
}
|
||||
|
||||
// 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) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
|
||||
// assert that user has entered an amount
|
||||
if user.StateKey != lnbits.UserHasEnteredAmount {
|
||||
log.Errorln("[lnurlPayHandlerSend] state keys don't match")
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return 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("[lnurlPayHandlerSend] 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 := &LnurlPayState{Base: storage.New(storage.ID(enterAmountData.ID))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
lnurlPayState := fn.(*LnurlPayState)
|
||||
|
||||
// LnurlPayState loaded
|
||||
|
||||
client, err := bot.GetHttpClient()
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
qs := callbackUrl.Query()
|
||||
// add amount to query string
|
||||
qs.Set("amount", strconv.FormatInt(lnurlPayState.Amount, 10)) // msat
|
||||
// add comment to query string
|
||||
if len(lnurlPayState.Comment) > 0 {
|
||||
qs.Set("comment", lnurlPayState.Comment)
|
||||
}
|
||||
|
||||
callbackUrl.RawQuery = qs.Encode()
|
||||
|
||||
res, err := client.Get(callbackUrl.String())
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
body, err := ioutil.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
var response2 lnurl.LNURLPayValues
|
||||
json.Unmarshal(body, &response2)
|
||||
if response2.Status == "ERROR" || len(response2.PR) < 1 {
|
||||
error_reason := "Could not receive invoice."
|
||||
if len(response2.Reason) > 0 {
|
||||
error_reason = response2.Reason
|
||||
}
|
||||
log.Errorf("[lnurlPayHandler] Error in LNURLPayValues: %s", error_reason)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
|
||||
return ctx, fmt.Errorf("Error in LNURLPayValues: %s", error_reason)
|
||||
}
|
||||
|
||||
lnurlPayState.LNURLPayValues = response2
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
|
||||
bot.Telegram.Delete(statusMsg)
|
||||
m.Text = fmt.Sprintf("/pay %s", response2.PR)
|
||||
return bot.payHandler(ctx, m)
|
||||
}
|
||||
|
||||
func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, address string, amount int64) (context.Context, error) {
|
||||
split := strings.Split(address, "@")
|
||||
if len(split) != 2 {
|
||||
return ctx, fmt.Errorf("lightning address format wrong")
|
||||
}
|
||||
host := strings.ToLower(split[1])
|
||||
name := strings.ToLower(split[0])
|
||||
|
||||
// convert address scheme into LNURL Bech32 format
|
||||
callback := fmt.Sprintf("https://%s/.well-known/lnurlp/%s", host, name)
|
||||
|
||||
log.Infof("[sendToLightningAddress] %s: callback: %s", GetUserStr(m.Sender), callback)
|
||||
|
||||
lnurl, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
if amount > 0 {
|
||||
// only when amount is given, we will also add a comment to the command
|
||||
// we do this because if the amount is not given, we will have to ask for it later
|
||||
// in the lnurl handler and we don't want to add another step where we ask for a comment
|
||||
// the command to pay to lnurl with comment is /lnurl <amount> <lnurl> <comment>
|
||||
// check if comment is presentin lnrul-p
|
||||
memo := GetMemoFromCommand(m.Text, 3)
|
||||
m.Text = fmt.Sprintf("/lnurl %d %s", amount, lnurl)
|
||||
// shorten comment to allowed length
|
||||
if len(memo) > 0 {
|
||||
m.Text = m.Text + " " + memo
|
||||
}
|
||||
} else {
|
||||
// no amount was given so we will just send the lnurl
|
||||
// this will invoke the "enter amount" dialog in the lnurl handler
|
||||
m.Text = fmt.Sprintf("/lnurl %s", lnurl)
|
||||
}
|
||||
bot.lnurlHandler(ctx, m)
|
||||
return ctx, nil
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"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"
|
||||
)
|
||||
|
||||
func (bot *TipBot) GetHttpClient() (*http.Client, error) {
|
||||
client := http.Client{}
|
||||
if internal.Configuration.Bot.HttpProxy != "" {
|
||||
proxyUrl, err := url.Parse(internal.Configuration.Bot.HttpProxy)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return nil, err
|
||||
}
|
||||
client.Transport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)}
|
||||
}
|
||||
return &client, nil
|
||||
}
|
||||
func (bot TipBot) cancelLnUrlHandler(c *tb.Callback) {
|
||||
}
|
||||
|
||||
// lnurlHandler is invoked on /lnurl command
|
||||
func (bot *TipBot) lnurlHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
// commands:
|
||||
// /lnurl
|
||||
// /lnurl <LNURL>
|
||||
// or /lnurl <amount> <LNURL>
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
log.Infof("[lnurlHandler] %s", m.Text)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
|
||||
// if only /lnurl is entered, show the lnurl of the user
|
||||
if m.Text == "/lnurl" {
|
||||
return bot.lnurlReceiveHandler(ctx, m)
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
// get rid of the URI prefix
|
||||
lnurlSplit = strings.TrimPrefix(lnurlSplit, "lightning:")
|
||||
|
||||
log.Debugf("[lnurlHandler] lnurlSplit: %s", lnurlSplit)
|
||||
// HandleLNURL by fiatjaf/go-lnurl
|
||||
_, params, err := bot.HandleLNURL(lnurlSplit)
|
||||
if err != nil {
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "LNURL error."))
|
||||
// bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
log.Warnf("[HandleLNURL] Error: %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
switch params.(type) {
|
||||
case lnurl.LNURLAuthParams:
|
||||
authParams := &LnurlAuthState{LNURLAuthParams: params.(lnurl.LNURLAuthParams)}
|
||||
log.Infof("[LNURL-auth] %s", authParams.LNURLAuthParams.Callback)
|
||||
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)
|
||||
default:
|
||||
if err == nil {
|
||||
err = fmt.Errorf("invalid LNURL type")
|
||||
}
|
||||
log.Warnln(err)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) UserGetLightningAddress(user *lnbits.User) (string, error) {
|
||||
if len(user.Telegram.Username) > 0 {
|
||||
return fmt.Sprintf("%s@%s", strings.ToLower(user.Telegram.Username), strings.ToLower(internal.Configuration.Bot.LNURLHostUrl.Hostname())), nil
|
||||
} else {
|
||||
lnaddr, err := bot.UserGetAnonLightningAddress(user)
|
||||
return lnaddr, err
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) UserGetAnonLightningAddress(user *lnbits.User) (string, error) {
|
||||
return fmt.Sprintf("%s@%s", fmt.Sprint(user.AnonIDSha256), strings.ToLower(internal.Configuration.Bot.LNURLHostUrl.Hostname())), nil
|
||||
}
|
||||
|
||||
func UserGetLNURL(user *lnbits.User) (string, error) {
|
||||
name := fmt.Sprint(user.UUID)
|
||||
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, name)
|
||||
log.Debugf("[lnurlReceiveHandler] %s's LNURL: %s", GetUserStr(user.Telegram), callback)
|
||||
|
||||
lnurlEncode, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return lnurlEncode, nil
|
||||
}
|
||||
|
||||
// lnurlReceiveHandler outputs the LNURL of the user
|
||||
func (bot TipBot) lnurlReceiveHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
fromUser := LoadUser(ctx)
|
||||
lnurlEncode, err := UserGetLNURL(fromUser)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to get LNURL: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlNoUsernameMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(lnurlEncode, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to create QR code for LNURL: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlReceiveInfoText"))
|
||||
// send the lnurl QR code
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lnurlEncode)})
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// fiatjaf/go-lnurl 1.8.4 with proxy
|
||||
func (bot TipBot) HandleLNURL(rawlnurl string) (string, lnurl.LNURLParams, error) {
|
||||
var err error
|
||||
var rawurl string
|
||||
|
||||
if name, domain, ok := lnurl.ParseInternetIdentifier(rawlnurl); ok {
|
||||
isOnion := strings.Index(domain, ".onion") == len(domain)-6
|
||||
rawurl = domain + "/.well-known/lnurlp/" + name
|
||||
if isOnion {
|
||||
rawurl = "http://" + rawurl
|
||||
} else {
|
||||
rawurl = "https://" + rawurl
|
||||
}
|
||||
} 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)
|
||||
if !ok {
|
||||
return "", nil,
|
||||
fmt.Errorf("invalid bech32-encoded lnurl: " + rawlnurl)
|
||||
}
|
||||
rawurl, err = lnurl.LNURLDecode(lnurl_str)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
}
|
||||
|
||||
parsed, err := url.Parse(rawurl)
|
||||
if err != nil {
|
||||
return rawurl, nil, err
|
||||
}
|
||||
|
||||
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
|
||||
// }
|
||||
|
||||
client, err := bot.GetHttpClient()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
resp, err := client.Get(rawurl)
|
||||
if err != nil {
|
||||
return rawurl, nil, err
|
||||
}
|
||||
if resp.StatusCode >= 300 {
|
||||
return rawurl, nil, fmt.Errorf("HTTP error: " + resp.Status)
|
||||
}
|
||||
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return rawurl, nil, err
|
||||
}
|
||||
|
||||
j := gjson.ParseBytes(b)
|
||||
if j.Get("status").String() == "ERROR" {
|
||||
return rawurl, nil, lnurl.LNURLErrorResponse{
|
||||
URL: parsed,
|
||||
Reason: j.Get("reason").String(),
|
||||
Status: "ERROR",
|
||||
}
|
||||
}
|
||||
|
||||
switch j.Get("tag").String() {
|
||||
case "withdrawRequest":
|
||||
value, err := lnurl.HandleWithdraw(b)
|
||||
return rawurl, value, err
|
||||
case "payRequest":
|
||||
value, err := lnurl.HandlePay(b)
|
||||
return rawurl, value, err
|
||||
// case "channelRequest":
|
||||
// value, err := lnurl.HandleChannel(b)
|
||||
// return rawurl, value, err
|
||||
default:
|
||||
return rawurl, nil, fmt.Errorf("Unkown LNURL response.")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
Message *tb.Message `json:"message"`
|
||||
duration time.Duration
|
||||
}
|
||||
|
||||
type MessageOption func(m *Message)
|
||||
|
||||
func WithDuration(duration time.Duration, tipBot *TipBot) MessageOption {
|
||||
return func(m *Message) {
|
||||
m.duration = duration
|
||||
go m.dispose(tipBot)
|
||||
}
|
||||
}
|
||||
|
||||
func NewMessage(m *tb.Message, opts ...MessageOption) *Message {
|
||||
msg := &Message{
|
||||
Message: m,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(msg)
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
func (msg Message) Key() string {
|
||||
return strconv.Itoa(msg.Message.ID)
|
||||
}
|
||||
|
||||
func (msg Message) dispose(tipBot *TipBot) {
|
||||
// do not delete messages from private chat
|
||||
if msg.Message.Private() {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
time.Sleep(msg.duration)
|
||||
tipBot.tryDeleteMessage(msg.Message)
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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/str"
|
||||
decodepay "github.com/fiatjaf/ln-decodepay"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
paymentConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelPay = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_pay")
|
||||
btnPay = paymentConfirmationMenu.Data("✅ Pay", "confirm_pay")
|
||||
)
|
||||
|
||||
func helpPayInvoiceUsage(ctx context.Context, errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(Translate(ctx, "payHelpText"), fmt.Sprintf("%s", errormsg))
|
||||
} else {
|
||||
return fmt.Sprintf(Translate(ctx, "payHelpText"), "")
|
||||
}
|
||||
}
|
||||
|
||||
type PayData struct {
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
Invoice string `json:"invoice"`
|
||||
Hash string `json:"hash"`
|
||||
Proof string `json:"proof"`
|
||||
Memo string `json:"memo"`
|
||||
Message string `json:"message"`
|
||||
Amount int64 `json:"amount"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
TelegramMessage *tb.Message `json:"telegrammessage"`
|
||||
}
|
||||
|
||||
// payHandler invoked on "/pay lnbc..." command
|
||||
func (bot *TipBot) payHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
if len(strings.Split(m.Text, " ")) < 2 {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, ""))
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
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())
|
||||
log.Errorln(errmsg)
|
||||
return ctx, errors.New(errors.InvalidSyntaxError, err)
|
||||
}
|
||||
paymentRequest = strings.ToLower(paymentRequest)
|
||||
// get rid of the URI prefix
|
||||
paymentRequest = strings.TrimPrefix(paymentRequest, "lightning:")
|
||||
|
||||
// decode invoice
|
||||
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())
|
||||
log.Errorln(errmsg)
|
||||
return ctx, errors.New(errors.InvalidSyntaxError, err)
|
||||
}
|
||||
amount := int64(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)
|
||||
}
|
||||
|
||||
// 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())
|
||||
log.Errorln(errmsg)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, errors.New(errors.GetBalanceError, err)
|
||||
}
|
||||
|
||||
if amount > balance {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "insufficientFundsMessage"), balance, amount))
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
// send warning that the invoice might fail due to missing fee reserve
|
||||
if float64(amount) > float64(balance)*0.99 {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "feeReserveMessage"))
|
||||
}
|
||||
|
||||
confirmText := fmt.Sprintf(Translate(ctx, "confirmPayInvoiceMessage"), amount)
|
||||
if len(bolt11.Description) > 0 {
|
||||
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(bolt11.Description))
|
||||
}
|
||||
|
||||
log.Infof("[/pay] Invoice entered. User: %s, amount: %d sat.", userStr, amount)
|
||||
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("pay-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
|
||||
|
||||
// // // create inline buttons
|
||||
payButton := paymentConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "confirm_pay", id)
|
||||
cancelButton := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_pay", id)
|
||||
|
||||
paymentConfirmationMenu.Inline(
|
||||
paymentConfirmationMenu.Row(
|
||||
payButton,
|
||||
cancelButton),
|
||||
)
|
||||
payMessage := bot.trySendMessageEditable(m.Chat, confirmText, paymentConfirmationMenu)
|
||||
payData := &PayData{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
From: user,
|
||||
Invoice: paymentRequest,
|
||||
Amount: int64(amount),
|
||||
Memo: bolt11.Description,
|
||||
Message: confirmText,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
TelegramMessage: payMessage,
|
||||
}
|
||||
// add result to persistent struct
|
||||
runtime.IgnoreError(payData.Set(payData, bot.Bunt))
|
||||
|
||||
SetUserState(user, bot, lnbits.UserStateConfirmPayment, paymentRequest)
|
||||
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)
|
||||
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
|
||||
}
|
||||
payData := sn.(*PayData)
|
||||
|
||||
// onnly the correct user can press
|
||||
if payData.From.Telegram.ID != c.Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
if !payData.Active {
|
||||
log.Errorf("[confirmPayHandler] send not active anymore")
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
defer payData.Set(payData, bot.Bunt)
|
||||
|
||||
// remove buttons from confirmation message
|
||||
// bot.tryEditMessage(c.Message, MarkdownEscape(payData.Message), &tb.ReplyMarkup{})
|
||||
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
|
||||
invoiceString := payData.Invoice
|
||||
|
||||
// reset state immediately
|
||||
ResetUserState(user, bot)
|
||||
|
||||
userStr := GetUserStr(c.Sender)
|
||||
|
||||
// update button text
|
||||
bot.tryEditMessage(
|
||||
c.Message,
|
||||
payData.Message,
|
||||
&tb.ReplyMarkup{
|
||||
InlineKeyboard: [][]tb.InlineButton{
|
||||
{tb.InlineButton{Text: i18n.Translate(payData.LanguageCode, "lnurlGettingUserMessage")}},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
log.Infof("[/pay] Attempting %s's invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
|
||||
// pay invoice
|
||||
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoiceString}, bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of %s: %s", userStr, err)
|
||||
err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
|
||||
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), err.Error()), &tb.ReplyMarkup{})
|
||||
// verbose error message, turned off for now
|
||||
// if len(err.Error()) == 0 {
|
||||
// err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
|
||||
// }
|
||||
// bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePaymentFailedMessage"), str.MarkdownEscape(err.Error())), &tb.ReplyMarkup{})
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
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"))
|
||||
} 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
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot *TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
|
||||
// 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
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelPaymentHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
payData := sn.(*PayData)
|
||||
// onnly the correct user can press
|
||||
if payData.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.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)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
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"
|
||||
)
|
||||
|
||||
// TryRecognizeInvoiceFromQrCode will try to read an invoice string from a qr code and invoke the payment handler.
|
||||
func TryRecognizeQrCode(img image.Image) (*gozxing.Result, error) {
|
||||
// check for qr code
|
||||
bmp, _ := gozxing.NewBinaryBitmapFromImage(img)
|
||||
// decode image
|
||||
qrReader := qrcode.NewQRCodeReader()
|
||||
result, err := qrReader.Decode(bmp, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload := strings.ToLower(result.String())
|
||||
if lightning.IsInvoice(payload) || lightning.IsLnurl(payload) {
|
||||
// create payment command payload
|
||||
// invoke payment confirmation handler
|
||||
return result, nil
|
||||
}
|
||||
return nil, fmt.Errorf("no codes found")
|
||||
}
|
||||
|
||||
// photoHandler is the handler function for every photo from a private chat that the bot receives
|
||||
func (bot *TipBot) photoHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
// 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
|
||||
}
|
||||
data, err := TryRecognizeQrCode(img)
|
||||
if err != nil {
|
||||
log.Errorf("[photoHandler] tryRecognizeQrCodes error: %v\n", err.Error())
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "photoQrNotRecognizedMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "photoQrRecognizedMessage"), data.String()))
|
||||
// invoke payment handler
|
||||
if lightning.IsInvoice(data.String()) {
|
||||
m.Text = fmt.Sprintf("/pay %s", data.String())
|
||||
return bot.payHandler(ctx, m)
|
||||
} else if lightning.IsLnurl(data.String()) {
|
||||
m.Text = fmt.Sprintf("/lnurl %s", data.String())
|
||||
return bot.lnurlHandler(ctx, m)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// DownloadProfilePicture downloads a profile picture from Telegram.
|
||||
// This is a public function because it is used in another package (lnurl)
|
||||
func DownloadProfilePicture(telegram *tb.Bot, user *tb.User) ([]byte, error) {
|
||||
photo, err := ProfilePhotosOf(telegram, user)
|
||||
if err != nil {
|
||||
log.Errorf("[DownloadProfilePicture] %v", err)
|
||||
return nil, err
|
||||
}
|
||||
if len(photo) == 0 {
|
||||
log.Error("[DownloadProfilePicture] No profile picture found")
|
||||
return nil, err
|
||||
}
|
||||
buf := new(bytes.Buffer)
|
||||
reader, err := telegram.GetFile(&photo[0].File)
|
||||
if err != nil {
|
||||
log.Errorf("[DownloadProfilePicture] %v", err)
|
||||
return nil, err
|
||||
}
|
||||
img, err := jpeg.Decode(reader)
|
||||
if err != nil {
|
||||
log.Errorf("[DownloadProfilePicture] %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// resize image
|
||||
img = resize.Thumbnail(160, 160, img, resize.Lanczos3)
|
||||
|
||||
err = jpeg.Encode(buf, img, nil)
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
var BotProfilePicture []byte
|
||||
|
||||
// downloadMyProfilePicture downloads the profile picture of the bot
|
||||
// and saves it in `BotProfilePicture`
|
||||
func (bot *TipBot) downloadMyProfilePicture() error {
|
||||
picture, err := DownloadProfilePicture(bot.Telegram, bot.Telegram.Me)
|
||||
if err != nil {
|
||||
log.Errorf("[downloadMyProfilePicture] %v", err)
|
||||
return err
|
||||
}
|
||||
BotProfilePicture = picture
|
||||
return nil
|
||||
}
|
||||
|
||||
// ProfilePhotosOf returns list of profile pictures for a user.
|
||||
func ProfilePhotosOf(bot *tb.Bot, user *tb.User) ([]tb.Photo, error) {
|
||||
params := map[string]interface {
|
||||
}{
|
||||
"user_id": user.Recipient(),
|
||||
"limit": 1,
|
||||
}
|
||||
|
||||
data, err := bot.Raw("getUserProfilePhotos", params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var resp struct {
|
||||
Result struct {
|
||||
Count int `json:"total_count"`
|
||||
Photos []tb.Photo `json:"photos"`
|
||||
}
|
||||
}
|
||||
if err := json.Unmarshal(data, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return resp.Result.Photos, nil
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"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/str"
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
sendConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelSend = sendConfirmationMenu.Data("🚫 Cancel", "cancel_send")
|
||||
btnSend = sendConfirmationMenu.Data("✅ Send", "confirm_send")
|
||||
)
|
||||
|
||||
func helpSendUsage(ctx context.Context, errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(Translate(ctx, "sendHelpText"), fmt.Sprintf("%s", errormsg))
|
||||
} else {
|
||||
return fmt.Sprintf(Translate(ctx, "sendHelpText"), "")
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) SendCheckSyntax(ctx context.Context, m *tb.Message) (bool, string) {
|
||||
arguments := strings.Split(m.Text, " ")
|
||||
if len(arguments) < 2 {
|
||||
return false, fmt.Sprintf(Translate(ctx, "sendSyntaxErrorMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
|
||||
type SendData struct {
|
||||
*storage.Base
|
||||
From *lnbits.User `json:"from"`
|
||||
ToTelegramId int64 `json:"to_telegram_id"`
|
||||
ToTelegramUser string `json:"to_telegram_user"`
|
||||
Memo string `json:"memo"`
|
||||
Message string `json:"message"`
|
||||
Amount int64 `json:"amount"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
}
|
||||
|
||||
// sendHandler invoked on "/send 123 @user" command
|
||||
func (bot *TipBot) sendHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
|
||||
// reset state immediately
|
||||
ResetUserState(user, bot)
|
||||
|
||||
// check and print all commands
|
||||
|
||||
// If the send is a reply, then trigger /tip handler
|
||||
if m.IsReply() && m.Chat.Type != tb.ChatPrivate {
|
||||
return bot.tipHandler(ctx, m)
|
||||
|
||||
}
|
||||
|
||||
// if 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)
|
||||
// info: /send 10 <user> DEMANDS an amount, while /send <ln@address.com> also works without
|
||||
// todo: /send <user> should also invoke amount input dialog if no amount is given
|
||||
|
||||
// CHECK whether first or second argument is a LIGHTNING ADDRESS
|
||||
arg := ""
|
||||
if len(strings.Split(m.Text, " ")) > 2 {
|
||||
arg, err = getArgumentFromCommand(m.Text, 2)
|
||||
} else if len(strings.Split(m.Text, " ")) == 2 {
|
||||
arg, err = getArgumentFromCommand(m.Text, 1)
|
||||
}
|
||||
if err == nil {
|
||||
if lightning.IsLightningAddress(arg) {
|
||||
// lightning address, send to that address
|
||||
ctx, err = bot.sendToLightningAddress(ctx, m, arg, amount)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
|
||||
// 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?
|
||||
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
|
||||
}
|
||||
|
||||
// ASSUME INTERNAL SEND TO TELEGRAM USER
|
||||
if err != nil || amount < 1 {
|
||||
errmsg := fmt.Sprintf("[/send] Error: Send amount not valid.")
|
||||
log.Warnln(errmsg)
|
||||
// immediately delete if the amount is bullshit
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpSendUsage(ctx, Translate(ctx, "sendValidAmountMessage")))
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// SEND COMMAND IS VALID
|
||||
// check for memo in command
|
||||
sendMemo := GetMemoFromCommand(m.Text, 3)
|
||||
|
||||
toUserStrMention := ""
|
||||
toUserStrWithoutAt := ""
|
||||
|
||||
// check for user in command, accepts user mention or plain username without @
|
||||
if len(m.Entities) > 1 && m.Entities[1].Type == "mention" {
|
||||
toUserStrMention = m.Text[m.Entities[1].Offset : m.Entities[1].Offset+m.Entities[1].Length]
|
||||
toUserStrWithoutAt = strings.TrimPrefix(toUserStrMention, "@")
|
||||
} else {
|
||||
toUserStrWithoutAt, err = getArgumentFromCommand(m.Text, 2)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
toUserStrWithoutAt = strings.TrimPrefix(toUserStrWithoutAt, "@")
|
||||
toUserStrMention = "@" + toUserStrWithoutAt
|
||||
}
|
||||
|
||||
err = bot.parseCmdDonHandler(ctx, m)
|
||||
if err == nil {
|
||||
return ctx, errors.Create(errors.InvalidSyntaxError)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// entire text of the inline object
|
||||
confirmText := fmt.Sprintf(Translate(ctx, "confirmSendMessage"), str.MarkdownEscape(toUserStrMention), amount)
|
||||
if len(sendMemo) > 0 {
|
||||
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmSendAppendMemo"), str.MarkdownEscape(sendMemo))
|
||||
}
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("send-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
|
||||
sendData := &SendData{
|
||||
From: user,
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Amount: int64(amount),
|
||||
ToTelegramId: toUserDb.Telegram.ID,
|
||||
ToTelegramUser: toUserStrWithoutAt,
|
||||
Memo: sendMemo,
|
||||
Message: confirmText,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
// save persistent struct
|
||||
runtime.IgnoreError(sendData.Set(sendData, bot.Bunt))
|
||||
|
||||
sendDataJson, err := json.Marshal(sendData)
|
||||
if err != nil {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
log.Printf("[/send] Error: %s\n", err.Error())
|
||||
bot.trySendMessage(m.Sender, fmt.Sprint(Translate(ctx, "errorTryLaterMessage")))
|
||||
return ctx, err
|
||||
}
|
||||
// save the send data to the Database
|
||||
// log.Debug(sendData)
|
||||
SetUserState(user, bot, lnbits.UserStateConfirmSend, string(sendDataJson))
|
||||
sendButton := sendConfirmationMenu.Data(Translate(ctx, "sendButtonMessage"), "confirm_send")
|
||||
cancelButton := sendConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_send")
|
||||
sendButton.Data = id
|
||||
cancelButton.Data = id
|
||||
|
||||
sendConfirmationMenu.Inline(
|
||||
sendConfirmationMenu.Row(
|
||||
sendButton,
|
||||
cancelButton),
|
||||
)
|
||||
if m.Private() {
|
||||
bot.trySendMessage(m.Chat, confirmText, sendConfirmationMenu)
|
||||
} 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)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
sendData := sn.(*SendData)
|
||||
// onnly the correct user can press
|
||||
if sendData.From.Telegram.ID != c.Sender.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
if !sendData.Active {
|
||||
log.Errorf("[acceptSendHandler] send not active anymore")
|
||||
// bot.tryDeleteMessage(c.Message)
|
||||
return ctx, errors.Create(errors.NotActiveError)
|
||||
}
|
||||
defer sendData.Set(sendData, bot.Bunt)
|
||||
|
||||
// // remove buttons from confirmation message
|
||||
// bot.tryEditMessage(c.Message, MarkdownEscape(sendData.Message), &tb.ReplyMarkup{})
|
||||
|
||||
// decode callback data
|
||||
// log.Debug("[send] Callback: %s", c.Data)
|
||||
from := LoadUser(ctx)
|
||||
ResetUserState(from, bot) // we don't need to check the statekey anymore like we did earlier
|
||||
|
||||
// information about the send
|
||||
toId := sendData.ToTelegramId
|
||||
toUserStrWithoutAt := sendData.ToTelegramUser
|
||||
amount := sendData.Amount
|
||||
sendMemo := sendData.Memo
|
||||
|
||||
// we can now get the wallets of both users
|
||||
to, err := GetLnbitsUser(&tb.User{ID: toId, Username: toUserStrWithoutAt}, *bot)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return ctx, err
|
||||
}
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
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.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())
|
||||
log.Errorln(errmsg)
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(sendData.LanguageCode, "sendErrorMessage"), &tb.ReplyMarkup{})
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
sendData.Inactivate(sendData, bot.Bunt)
|
||||
|
||||
log.Infof("[💸 send] Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
|
||||
// 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))
|
||||
} else {
|
||||
// if the command was invoked in group chat
|
||||
bot.trySendMessage(c.Sender, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
|
||||
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendPublicSentMessage"), amount, fromUserStrMd, toUserStrMd), &tb.ReplyMarkup{})
|
||||
}
|
||||
// send memo if it was present
|
||||
if len(sendMemo) > 0 {
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf("✉️ %s", str.MarkdownEscape(sendMemo)))
|
||||
}
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
|
||||
// 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)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
sendData := sn.(*SendData)
|
||||
// onnly the correct user can press
|
||||
if sendData.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.tryDeleteMessage(c.Message)
|
||||
bot.trySendMessage(c.Message.Chat, i18n.Translate(sendData.LanguageCode, "sendCancelledMessage"))
|
||||
sendData.Inactivate(sendData, bot.Bunt)
|
||||
return ctx, nil
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,286 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "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"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func (bot TipBot) startHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
if !m.Private() {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
// ATTENTION: DO NOT CALL ANY HANDLER BEFORE THE WALLET IS CREATED
|
||||
// WILL RESULT IN AN ENDLESS LOOP OTHERWISE
|
||||
// bot.helpHandler(m)
|
||||
log.Printf("[⭐️ /start] New user: %s (%d)\n", GetUserStr(m.Sender), m.Sender.ID)
|
||||
walletCreationMsg := bot.trySendMessageEditable(m.Sender, Translate(ctx, "startSettingWalletMessage"))
|
||||
user, err := bot.initWallet(m.Sender)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[startHandler] Error with initWallet: %s", err.Error()))
|
||||
bot.tryEditMessage(walletCreationMsg, Translate(ctx, "startWalletErrorMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
bot.tryDeleteMessage(walletCreationMsg)
|
||||
ctx = context.WithValue(ctx, "user", user)
|
||||
bot.helpHandler(ctx, m)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "startWalletReadyMessage"))
|
||||
bot.balanceHandler(ctx, m)
|
||||
|
||||
// send the user a warning about the fact that they need to set a username
|
||||
if len(m.Sender.Username) == 0 {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "startNoUsernameMessage"), tb.NoPreview)
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
|
||||
user, err := GetUser(tguser, bot)
|
||||
if stderrors.Is(err, gorm.ErrRecordNotFound) {
|
||||
user = &lnbits.User{Telegram: tguser}
|
||||
err = bot.createWallet(user)
|
||||
if err != nil {
|
||||
return user, err
|
||||
}
|
||||
// set user initialized
|
||||
user, err := GetUser(tguser, bot)
|
||||
user.Initialized = true
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
|
||||
return user, err
|
||||
}
|
||||
} else if !user.Initialized {
|
||||
// update all tip tooltips (with the "initialize me" message) that this user might have received before
|
||||
tipTooltipInitializedHandler(user.Telegram, bot)
|
||||
user.Initialized = true
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
|
||||
return user, err
|
||||
}
|
||||
} else if user.Initialized {
|
||||
// wallet is already initialized
|
||||
return user, nil
|
||||
} else {
|
||||
err = fmt.Errorf("could not initialize wallet")
|
||||
return user, err
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (bot TipBot) createWallet(user *lnbits.User) error {
|
||||
UserStr := GetUserStr(user.Telegram)
|
||||
u, err := bot.Client.CreateUserWithInitialWallet(strconv.FormatInt(user.Telegram.ID, 10),
|
||||
fmt.Sprintf("%d (%s)", user.Telegram.ID, UserStr),
|
||||
internal.Configuration.Lnbits.AdminId,
|
||||
UserStr)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err.Error())
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
user.Wallet = &lnbits.Wallet{}
|
||||
user.ID = u.ID
|
||||
user.Name = u.Name
|
||||
wallet, err := bot.Client.Wallets(*user)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err.Error())
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
user.Wallet = &wallet[0]
|
||||
|
||||
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
|
||||
user.AnonIDSha256 = str.AnonIdSha256(user)
|
||||
user.UUID = str.UUIDSha256(user)
|
||||
|
||||
user.Initialized = false
|
||||
user.CreatedAt = time.Now()
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err.Error())
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type StateCallbackMessage map[lnbits.UserStateKey]func(ctx context.Context, m *tb.Message) (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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
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"
|
||||
)
|
||||
|
||||
// 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)...)
|
||||
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())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) tryReplyMessage(to *tb.Message, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
rate.CheckLimit(to)
|
||||
msg, err := bot.Telegram.Reply(to, what, bot.appendMainMenu(to.Chat.ID, to, options)...)
|
||||
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...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) tryDeleteMessage(msg tb.Editable) {
|
||||
if !allowedToPerformAction(bot, msg, isAdminAndCanDelete) {
|
||||
return
|
||||
}
|
||||
rate.CheckLimit(msg)
|
||||
err := bot.Telegram.Delete(msg)
|
||||
if err != nil {
|
||||
log.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
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
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"
|
||||
)
|
||||
|
||||
func (bot *TipBot) anyTextHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return ctx, errors.Create(errors.NoPrivateChatError)
|
||||
}
|
||||
|
||||
// check if user is in Database, if not, initialize wallet
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil || !user.Initialized {
|
||||
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)
|
||||
}
|
||||
|
||||
// could be an invoice
|
||||
anyText := strings.ToLower(m.Text)
|
||||
if lightning.IsInvoice(anyText) {
|
||||
m.Text = "/pay " + anyText
|
||||
return bot.payHandler(ctx, m)
|
||||
}
|
||||
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)
|
||||
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)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func helpTipUsage(ctx context.Context, errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(Translate(ctx, "tipHelpText"), fmt.Sprintf("%s", errormsg))
|
||||
} else {
|
||||
return fmt.Sprintf(Translate(ctx, "tipHelpText"), "")
|
||||
}
|
||||
}
|
||||
|
||||
func TipCheckSyntax(ctx context.Context, m *tb.Message) (bool, string) {
|
||||
arguments := strings.Split(m.Text, " ")
|
||||
if len(arguments) < 2 {
|
||||
return false, Translate(ctx, "tipEnterAmountMessage")
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
|
||||
func (bot *TipBot) tipHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return ctx, fmt.Errorf("user has no wallet")
|
||||
}
|
||||
|
||||
// only if message is a reply
|
||||
if !m.IsReply() {
|
||||
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)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// get tip amount
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if err != nil || amount < 1 {
|
||||
errmsg := fmt.Sprintf("[/tip] Error: Tip amount not valid.")
|
||||
// immediately delete if the amount is bullshit
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpTipUsage(ctx, Translate(ctx, "tipValidAmountMessage")))
|
||||
log.Warnln(errmsg)
|
||||
return ctx, errors.Create(errors.InvalidAmountError)
|
||||
}
|
||||
|
||||
err = bot.parseCmdDonHandler(ctx, m)
|
||||
if err == nil {
|
||||
return ctx, fmt.Errorf("invalid parseCmdDonHandler")
|
||||
}
|
||||
// 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")
|
||||
}
|
||||
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
|
||||
if _, exists := bot.UserExists(to.Telegram); !exists {
|
||||
log.Infof("[/tip] User %s has no wallet.", toUserStr)
|
||||
to, err = bot.CreateWalletForTelegramUser(to.Telegram)
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[/tip] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return ctx, fmt.Errorf("could not create wallet for %s", toUserStr)
|
||||
}
|
||||
}
|
||||
|
||||
// check for memo in command
|
||||
tipMemo := ""
|
||||
if len(strings.Split(m.Text, " ")) > 2 {
|
||||
tipMemo = strings.SplitN(m.Text, " ", 3)[2]
|
||||
if len(tipMemo) > 200 {
|
||||
tipMemo = tipMemo[:200]
|
||||
tipMemo = tipMemo + "..."
|
||||
}
|
||||
}
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("Tip from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
t := NewTransaction(bot, from, to, amount, TransactionType("tip"), TransactionChat(m.Chat))
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf("%s %s", Translate(ctx, "tipErrorMessage"), err))
|
||||
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err.Error())
|
||||
log.Warnln(errMsg)
|
||||
return ctx, fmt.Errorf("could not create wallet for %s", toUserStr)
|
||||
}
|
||||
|
||||
// update tooltip if necessary
|
||||
messageHasTip := tipTooltipHandler(m, bot, amount, to.Initialized)
|
||||
|
||||
log.Infof("[💸 tip] Tip 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))
|
||||
|
||||
// forward tipped message to user once
|
||||
if !messageHasTip {
|
||||
bot.tryForwardMessage(to.Telegram, m.ReplyTo, tb.Silent)
|
||||
}
|
||||
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "tipReceivedMessage"), fromUserStrMd, amount))
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
inlineTipjarMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: false}
|
||||
btnCancelInlineTipjar = inlineTipjarMenu.Data("🚫", "cancel_tipjar_inline")
|
||||
btnAcceptInlineTipjar = inlineTipjarMenu.Data("💸 Pay", "confirm_tipjar_inline")
|
||||
)
|
||||
|
||||
type InlineTipjar struct {
|
||||
*storage.Base
|
||||
Message string `json:"inline_tipjar_message"`
|
||||
Amount int64 `json:"inline_tipjar_amount"`
|
||||
GivenAmount int64 `json:"inline_tipjar_givenamount"`
|
||||
PerUserAmount int64 `json:"inline_tipjar_peruseramount"`
|
||||
To *lnbits.User `json:"inline_tipjar_to"`
|
||||
From []*lnbits.User `json:"inline_tipjar_from"`
|
||||
Memo string `json:"inline_tipjar_memo"`
|
||||
NTotal int `json:"inline_tipjar_ntotal"`
|
||||
NGiven int `json:"inline_tipjar_ngiven"`
|
||||
LanguageCode string `json:"languagecode"`
|
||||
}
|
||||
|
||||
func (bot TipBot) mapTipjarLanguage(ctx context.Context, command string) context.Context {
|
||||
if len(strings.Split(command, " ")) > 1 {
|
||||
c := strings.Split(command, " ")[0][1:] // cut the /
|
||||
ctx = bot.commandTranslationMap(ctx, c)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (bot TipBot) createTipjar(ctx context.Context, text string, sender *tb.User) (*InlineTipjar, error) {
|
||||
amount, err := decodeAmountFromCommand(text)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.DecodeAmountError, err)
|
||||
}
|
||||
peruserStr, err := getArgumentFromCommand(text, 2)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.DecodePerUserAmountError, err)
|
||||
}
|
||||
perUserAmount, err := getAmount(peruserStr)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.InvalidAmountError, err)
|
||||
}
|
||||
if perUserAmount < 1 || amount%perUserAmount != 0 {
|
||||
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("invalid amount per user"))
|
||||
}
|
||||
nTotal := int(amount / perUserAmount)
|
||||
toUser := LoadUser(ctx)
|
||||
// toUserStr := GetUserStr(sender)
|
||||
// // check for memo in command
|
||||
memo := GetMemoFromCommand(text, 3)
|
||||
|
||||
inlineMessage := fmt.Sprintf(
|
||||
Translate(ctx, "inlineTipjarMessage"),
|
||||
perUserAmount,
|
||||
GetUserStrMd(toUser.Telegram),
|
||||
0,
|
||||
amount,
|
||||
0,
|
||||
MakeTipjarbar(0, amount),
|
||||
)
|
||||
if len(memo) > 0 {
|
||||
inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineTipjarAppendMemo"), memo)
|
||||
}
|
||||
id := fmt.Sprintf("tipjar:%s:%d", RandStringRunes(10), amount)
|
||||
|
||||
return &InlineTipjar{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Message: inlineMessage,
|
||||
Amount: amount,
|
||||
To: toUser,
|
||||
Memo: memo,
|
||||
PerUserAmount: perUserAmount,
|
||||
NTotal: nTotal,
|
||||
NGiven: 0,
|
||||
GivenAmount: 0,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}, nil
|
||||
|
||||
}
|
||||
func (bot TipBot) makeTipjar(ctx context.Context, m *tb.Message, query bool) (*InlineTipjar, error) {
|
||||
tipjar, err := bot.createTipjar(ctx, m.Text, m.Sender)
|
||||
if err != nil {
|
||||
switch err.(errors.TipBotError).Code {
|
||||
case errors.DecodeAmountError:
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineTipjarHelpText"), Translate(ctx, "inlineTipjarInvalidAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.DecodePerUserAmountError:
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineTipjarHelpText"), ""))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.InvalidAmountError:
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineTipjarHelpText"), Translate(ctx, "inlineTipjarInvalidAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.InvalidAmountPerUserError:
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineTipjarHelpText"), Translate(ctx, "inlineTipjarInvalidPeruserAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.GetBalanceError:
|
||||
// log.Errorln(err.Error())
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
case errors.BalanceToLowError:
|
||||
// log.Errorf(err.Error())
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "inlineSendBalanceLowMessage"))
|
||||
bot.tryDeleteMessage(m)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return tipjar, err
|
||||
}
|
||||
|
||||
func (bot TipBot) makeQueryTipjar(ctx context.Context, q *tb.Query, query bool) (*InlineTipjar, error) {
|
||||
tipjar, err := bot.createTipjar(ctx, q.Text, &q.From)
|
||||
if err != nil {
|
||||
switch err.(errors.TipBotError).Code {
|
||||
case errors.DecodeAmountError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.DecodePerUserAmountError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.InvalidAmountError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.InvalidAmountPerUserError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineTipjarInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.GetBalanceError:
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryTipjarTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
case errors.BalanceToLowError:
|
||||
log.Errorf(err.Error())
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryTipjarDescription"), bot.Telegram.Me.Username))
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return tipjar, err
|
||||
}
|
||||
|
||||
func (bot TipBot) makeTipjarKeyboard(ctx context.Context, inlineTipjar *InlineTipjar) *tb.ReplyMarkup {
|
||||
inlineTipjarMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
// slice of buttons
|
||||
buttons := make([]tb.Btn, 0)
|
||||
cancelInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_tipjar_inline", inlineTipjar.ID)
|
||||
buttons = append(buttons, cancelInlineTipjarButton)
|
||||
acceptInlineTipjarButton := inlineTipjarMenu.Data(Translate(ctx, "payReceiveButtonMessage"), "confirm_tipjar_inline", inlineTipjar.ID)
|
||||
buttons = append(buttons, acceptInlineTipjarButton)
|
||||
|
||||
inlineTipjarMenu.Inline(
|
||||
inlineTipjarMenu.Row(buttons...))
|
||||
return inlineTipjarMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) tipjarHandler(ctx context.Context, m *tb.Message) (context.Context, error) {
|
||||
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)
|
||||
}
|
||||
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
|
||||
}
|
||||
toUserStr := GetUserStr(m.Sender)
|
||||
bot.trySendMessage(m.Chat, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
|
||||
log.Infof("[tipjar] %s created tipjar %s: %d sat (%d per user)", toUserStr, inlineTipjar.ID, inlineTipjar.Amount, inlineTipjar.PerUserAmount)
|
||||
return ctx, inlineTipjar.Set(inlineTipjar, bot.Bunt)
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) (context.Context, error) {
|
||||
inlineTipjar, err := bot.makeQueryTipjar(ctx, q, false)
|
||||
if err != nil {
|
||||
// log.Errorf("[tipjar] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
urls := []string{
|
||||
queryImage,
|
||||
}
|
||||
results := make(tb.Results, len(urls)) // []tb.Result
|
||||
for i, url := range urls {
|
||||
result := &tb.ArticleResult{
|
||||
// URL: url,
|
||||
Text: inlineTipjar.Message,
|
||||
Title: fmt.Sprintf(TranslateUser(ctx, "inlineResultTipjarTitle"), inlineTipjar.Amount),
|
||||
Description: TranslateUser(ctx, "inlineResultTipjarDescription"),
|
||||
// required for photos
|
||||
ThumbURL: url,
|
||||
}
|
||||
result.ReplyMarkup = &tb.InlineKeyboardMarkup{InlineKeyboard: bot.makeTipjarKeyboard(ctx, inlineTipjar).InlineKeyboard}
|
||||
results[i] = result
|
||||
// needed to set a unique string ID for each result
|
||||
results[i].SetResultID(inlineTipjar.ID)
|
||||
|
||||
bot.Cache.Set(inlineTipjar.ID, inlineTipjar, &store.Options{Expiration: 5 * time.Minute})
|
||||
log.Infof("[tipjar] %s created inline tipjar %s: %d sat (%d per user)", GetUserStr(inlineTipjar.To.Telegram), inlineTipjar.ID, inlineTipjar.Amount, inlineTipjar.PerUserAmount)
|
||||
}
|
||||
|
||||
err = bot.Telegram.Answer(q, &tb.QueryResponse{
|
||||
Results: results,
|
||||
CacheTime: 1,
|
||||
IsPersonal: true,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback) (context.Context, error) {
|
||||
from := LoadUser(ctx)
|
||||
if from.Wallet == nil {
|
||||
return ctx, errors.Create(errors.UserNoWalletError)
|
||||
}
|
||||
tx := &InlineTipjar{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
// log.Errorf("[tipjar] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
inlineTipjar := fn.(*InlineTipjar)
|
||||
to := inlineTipjar.To
|
||||
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)
|
||||
}
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return ctx, errors.Create(errors.SelfPaymentError)
|
||||
}
|
||||
// // check if to user has already given to the tipjar
|
||||
for _, a := range inlineTipjar.From {
|
||||
if a.Telegram.ID == from.Telegram.ID {
|
||||
// to user is already in To slice, has taken from facuet
|
||||
// log.Infof("[tipjar] %s already gave to tipjar %s", GetUserStr(to.Telegram), inlineTipjar.ID)
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
}
|
||||
|
||||
defer inlineTipjar.Set(inlineTipjar, bot.Bunt)
|
||||
|
||||
if inlineTipjar.GivenAmount < inlineTipjar.Amount {
|
||||
toUserStrMd := GetUserStrMd(to.Telegram)
|
||||
fromUserStrMd := GetUserStrMd(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("Tipjar from %s to %s (%d sat).", fromUserStr, toUserStr, inlineTipjar.PerUserAmount)
|
||||
t := NewTransaction(bot, from, to, inlineTipjar.PerUserAmount, TransactionType("tipjar"))
|
||||
t.Memo = transactionMemo
|
||||
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendErrorMessage"))
|
||||
errMsg := fmt.Sprintf("[tipjar] Transaction failed: %s", err.Error())
|
||||
log.Errorln(errMsg)
|
||||
return ctx, errors.New(errors.UnknownError, err)
|
||||
}
|
||||
|
||||
log.Infof("[💸 tipjar] Tipjar %s from %s to %s (%d sat).", inlineTipjar.ID, fromUserStr, toUserStr, inlineTipjar.PerUserAmount)
|
||||
inlineTipjar.NGiven += 1
|
||||
inlineTipjar.From = append(inlineTipjar.From, from)
|
||||
inlineTipjar.GivenAmount = inlineTipjar.GivenAmount + inlineTipjar.PerUserAmount
|
||||
|
||||
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))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[tipjar] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
|
||||
// build tipjar message
|
||||
inlineTipjar.Message = fmt.Sprintf(
|
||||
i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarMessage"),
|
||||
inlineTipjar.PerUserAmount,
|
||||
GetUserStrMd(inlineTipjar.To.Telegram),
|
||||
inlineTipjar.GivenAmount,
|
||||
inlineTipjar.Amount,
|
||||
inlineTipjar.NGiven,
|
||||
MakeTipjarbar(inlineTipjar.GivenAmount, inlineTipjar.Amount),
|
||||
)
|
||||
memo := inlineTipjar.Memo
|
||||
if len(memo) > 0 {
|
||||
inlineTipjar.Message = inlineTipjar.Message + fmt.Sprintf(i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarAppendMemo"), memo)
|
||||
}
|
||||
// update message
|
||||
log.Infoln(inlineTipjar.Message)
|
||||
bot.tryEditMessage(c.Message, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
|
||||
}
|
||||
if inlineTipjar.GivenAmount >= inlineTipjar.Amount {
|
||||
// tipjar is full
|
||||
inlineTipjar.Message = fmt.Sprintf(
|
||||
i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarEndedMessage"),
|
||||
GetUserStrMd(inlineTipjar.To.Telegram),
|
||||
inlineTipjar.Amount,
|
||||
inlineTipjar.NGiven,
|
||||
)
|
||||
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)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineTipjarHandler] %s", err.Error())
|
||||
return ctx, err
|
||||
}
|
||||
inlineTipjar := fn.(*InlineTipjar)
|
||||
if c.Sender.ID != inlineTipjar.To.Telegram.ID {
|
||||
return ctx, errors.Create(errors.UnknownError)
|
||||
}
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
|
||||
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/tidwall/buntdb"
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
tooltipChatWithBotMessage = "🗑 Chat with %s 👈 to manage your wallet."
|
||||
tooltipAndOthersMessage = " ... and others"
|
||||
tooltipMultipleTipsMessage = "%s (%d tips by %s)"
|
||||
tooltipSingleTipMessage = "%s (by %s)"
|
||||
tooltipTipAmountMessage = "🏅 %d sat"
|
||||
)
|
||||
|
||||
type TipTooltip struct {
|
||||
Message
|
||||
ID string `json:"id"`
|
||||
TipAmount int64 `json:"tip_amount"`
|
||||
Ntips int `json:"ntips"`
|
||||
LastTip time.Time `json:"last_tip"`
|
||||
Tippers []*tb.User `json:"tippers"`
|
||||
}
|
||||
|
||||
func (ttt TipTooltip) Key() string {
|
||||
return fmt.Sprintf("tip-tool-tip:%s", ttt.ID)
|
||||
}
|
||||
|
||||
const maxNamesInTipperMessage = 5
|
||||
|
||||
type TipTooltipOption func(m *TipTooltip)
|
||||
|
||||
func TipAmount(amount int64) TipTooltipOption {
|
||||
return func(m *TipTooltip) {
|
||||
m.TipAmount = amount
|
||||
}
|
||||
}
|
||||
func Tips(nTips int) TipTooltipOption {
|
||||
return func(m *TipTooltip) {
|
||||
m.LastTip = time.Now()
|
||||
m.Ntips = nTips
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(tipTooltip)
|
||||
}
|
||||
return tipTooltip
|
||||
|
||||
}
|
||||
|
||||
// getUpdatedTipTooltipMessage will return the full tip tool tip
|
||||
func (ttt TipTooltip) getUpdatedTipTooltipMessage(botUserName string, notInitializedWallet bool) string {
|
||||
tippersStr := getTippersString(ttt.Tippers)
|
||||
tipToolTipMessage := fmt.Sprintf(tooltipTipAmountMessage, ttt.TipAmount)
|
||||
if len(ttt.Tippers) > 1 {
|
||||
tipToolTipMessage = fmt.Sprintf(tooltipMultipleTipsMessage, tipToolTipMessage, ttt.Ntips, tippersStr)
|
||||
} else {
|
||||
tipToolTipMessage = fmt.Sprintf(tooltipSingleTipMessage, tipToolTipMessage, tippersStr)
|
||||
}
|
||||
|
||||
if notInitializedWallet {
|
||||
tipToolTipMessage = tipToolTipMessage + fmt.Sprintf("\n%s", fmt.Sprintf(tooltipChatWithBotMessage, botUserName))
|
||||
}
|
||||
return tipToolTipMessage
|
||||
}
|
||||
|
||||
// getTippersString joins all tippers username or Telegram id's as mentions (@username or [inline mention of a user](tg://user?id=123456789))
|
||||
func getTippersString(tippers []*tb.User) string {
|
||||
var tippersStr string
|
||||
for _, uniqueUser := range tippers {
|
||||
userStr := GetUserStrMd(uniqueUser)
|
||||
tippersStr += fmt.Sprintf("%s, ", userStr)
|
||||
}
|
||||
// get rid of the trailing comma
|
||||
if len(tippersStr) > 2 {
|
||||
tippersStr = tippersStr[:len(tippersStr)-2]
|
||||
}
|
||||
tippersSlice := strings.Split(tippersStr, " ")
|
||||
// crop the message to the max length
|
||||
if len(tippersSlice) > maxNamesInTipperMessage {
|
||||
// tippersStr = tippersStr[:50]
|
||||
tippersStr = strings.Join(tippersSlice[:maxNamesInTipperMessage], " ")
|
||||
tippersStr = tippersStr + tooltipAndOthersMessage
|
||||
}
|
||||
return tippersStr
|
||||
}
|
||||
|
||||
// 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}})
|
||||
err := bot.Bunt.Get(message)
|
||||
if err != nil {
|
||||
return false, message
|
||||
}
|
||||
return true, message
|
||||
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// 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)
|
||||
if hasTip {
|
||||
// update the tooltip with new tippers
|
||||
err := ttt.updateTooltip(bot, m.Sender, amount, !initializedWallet)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
// could not update the message (return false to )
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
newToolTip(m, bot, amount, initializedWallet)
|
||||
}
|
||||
// first call will return false, every following call will return true
|
||||
return hasTip
|
||||
}
|
||||
|
||||
func newToolTip(m *tb.Message, bot *TipBot, amount int64, initializedWallet bool) {
|
||||
tipmsg := fmt.Sprintf(tooltipTipAmountMessage, amount)
|
||||
userStr := GetUserStrMd(m.Sender)
|
||||
tipmsg = fmt.Sprintf(tooltipSingleTipMessage, tipmsg, userStr)
|
||||
|
||||
if !initializedWallet {
|
||||
tipmsg = tipmsg + fmt.Sprintf("\n%s", fmt.Sprintf(tooltipChatWithBotMessage, GetUserStrMd(bot.Telegram.Me)))
|
||||
}
|
||||
msg := bot.tryReplyMessage(m.ReplyTo, tipmsg, tb.Silent)
|
||||
message := NewTipTooltip(msg, TipAmount(amount), Tips(1))
|
||||
message.Tippers = appendUinqueUsersToSlice(message.Tippers, m.Sender)
|
||||
runtime.IgnoreError(bot.Bunt.Set(message))
|
||||
log.Debugf("[newToolTip]: New reply message: %d (Bunt: %s)", msg.ID, message.Key())
|
||||
}
|
||||
|
||||
// updateToolTip updates existing tip tool tip in Telegram
|
||||
func (ttt *TipTooltip) updateTooltip(bot *TipBot, user *tb.User, amount int64, 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())
|
||||
return bot.Bunt.Set(ttt)
|
||||
}
|
||||
|
||||
// tipTooltipInitializedHandler is called when the user initializes the wallet
|
||||
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")
|
||||
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)
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
return err
|
||||
}))
|
||||
}
|
||||
|
||||
// editTooltip updates the tooltip message with the new tip amount and tippers and edits it
|
||||
func (ttt *TipTooltip) editTooltip(bot *TipBot, notInitializedWallet bool) {
|
||||
tipToolTip := ttt.getUpdatedTipTooltipMessage(GetUserStrMd(bot.Telegram.Me), notInitializedWallet)
|
||||
bot.tryEditMessage(ttt.Message.Message, tipToolTip)
|
||||
// ttt.Message.Message.Text = m.Text
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
package main
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -44,8 +44,8 @@ func Test_getTippersString(t *testing.T) {
|
||||
|
||||
func TestMessage_getTooltipMessage(t *testing.T) {
|
||||
type fields struct {
|
||||
Message *tb.Message
|
||||
TipAmount int
|
||||
Message Message
|
||||
TipAmount int64
|
||||
Ntips int
|
||||
LastTip time.Time
|
||||
Tippers []*tb.User
|
||||
@@ -65,27 +65,27 @@ func TestMessage_getTooltipMessage(t *testing.T) {
|
||||
{
|
||||
name: "1",
|
||||
args: args{botUserName: "@test-bot", notInitializedWallet: true},
|
||||
fields: fields{Message: &tb.Message{}, TipAmount: 10, Ntips: 1, Tippers: append(tippers, tipper1)},
|
||||
fields: fields{Message: Message{}, TipAmount: 10, Ntips: 1, Tippers: append(tippers, tipper1)},
|
||||
want: "🏅 10 sat (by @username1)\n🗑 Chat with @test-bot to manage your wallet.",
|
||||
},
|
||||
{
|
||||
name: "2",
|
||||
args: args{botUserName: "@test-bot", notInitializedWallet: true},
|
||||
fields: fields{Message: &tb.Message{}, TipAmount: 100, Ntips: 6, Tippers: append(tippers, tipper1, tipper2, tipper3, tipper4, tipper5, tipper6)},
|
||||
fields: fields{Message: Message{}, TipAmount: 100, Ntips: 6, Tippers: append(tippers, tipper1, tipper2, tipper3, tipper4, tipper5, tipper6)},
|
||||
want: "🏅 100 sat (6 tips by @username1, @username2, @username3, @username4, @username5, ... and others)\n🗑 Chat with @test-bot to manage your wallet.",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
x := Message{
|
||||
x := TipTooltip{
|
||||
Message: tt.fields.Message,
|
||||
TipAmount: tt.fields.TipAmount,
|
||||
Ntips: tt.fields.Ntips,
|
||||
LastTip: tt.fields.LastTip,
|
||||
Tippers: tt.fields.Tippers,
|
||||
}
|
||||
if got := x.getTooltipMessage(tt.args.botUserName, tt.args.notInitializedWallet); got != tt.want {
|
||||
t.Errorf("getTooltipMessage() = %v, want %v", got, tt.want)
|
||||
if got := x.getUpdatedTipTooltipMessage(tt.args.botUserName, tt.args.notInitializedWallet); got != tt.want {
|
||||
t.Errorf("getUpdatedTipTooltipMessage() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type Transaction struct {
|
||||
ID uint `gorm:"primarykey"`
|
||||
Time time.Time `json:"time"`
|
||||
Bot *TipBot `gorm:"-"`
|
||||
From *lnbits.User `json:"from" gorm:"-"`
|
||||
To *lnbits.User `json:"to" gorm:"-"`
|
||||
FromId int64 `json:"from_id" `
|
||||
ToId int64 `json:"to_id" `
|
||||
FromUser string `json:"from_user"`
|
||||
ToUser string `json:"to_user"`
|
||||
Type string `json:"type"`
|
||||
Amount int64 `json:"amount"`
|
||||
ChatID int64 `json:"chat_id"`
|
||||
ChatName string `json:"chat_name"`
|
||||
Memo string `json:"memo"`
|
||||
Success bool `json:"success"`
|
||||
FromWallet string `json:"from_wallet"`
|
||||
ToWallet string `json:"to_wallet"`
|
||||
FromLNbitsID string `json:"from_lnbits"`
|
||||
ToLNbitsID string `json:"to_lnbits"`
|
||||
Invoice lnbits.BitInvoice `gorm:"embedded;embeddedPrefix:invoice_"`
|
||||
}
|
||||
|
||||
type TransactionOption func(t *Transaction)
|
||||
|
||||
func TransactionChat(chat *tb.Chat) TransactionOption {
|
||||
return func(t *Transaction) {
|
||||
t.ChatID = chat.ID
|
||||
t.ChatName = chat.Title
|
||||
}
|
||||
}
|
||||
|
||||
func TransactionType(transactionType string) TransactionOption {
|
||||
return func(t *Transaction) {
|
||||
t.Type = transactionType
|
||||
}
|
||||
}
|
||||
|
||||
func NewTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int64, opts ...TransactionOption) *Transaction {
|
||||
t := &Transaction{
|
||||
Bot: bot,
|
||||
From: from,
|
||||
To: to,
|
||||
FromUser: GetUserStr(from.Telegram),
|
||||
ToUser: GetUserStr(to.Telegram),
|
||||
FromId: from.Telegram.ID,
|
||||
ToId: to.Telegram.ID,
|
||||
Amount: amount,
|
||||
Memo: "Powered by @LightningTipBot",
|
||||
Time: time.Now(),
|
||||
Success: false,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(t)
|
||||
}
|
||||
return t
|
||||
|
||||
}
|
||||
|
||||
func (t *Transaction) Send() (success bool, err error) {
|
||||
success, err = t.SendTransaction(t.Bot, t.From, t.To, t.Amount, t.Memo)
|
||||
if success {
|
||||
t.Success = success
|
||||
}
|
||||
|
||||
// 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())
|
||||
log.Errorln(errMsg)
|
||||
}
|
||||
return success, err
|
||||
}
|
||||
|
||||
func (t *Transaction) SendTransaction(bot *TipBot, from *lnbits.User, to *lnbits.User, amount int64, memo string) (bool, error) {
|
||||
fromUserStr := GetUserStr(from.Telegram)
|
||||
toUserStr := GetUserStr(to.Telegram)
|
||||
|
||||
t.FromWallet = from.Wallet.ID
|
||||
t.FromLNbitsID = from.ID
|
||||
|
||||
// check if fromUser has balance
|
||||
balance, err := bot.GetUserBalance(from)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return false, err
|
||||
}
|
||||
// check if fromUser has balance
|
||||
if balance < amount {
|
||||
errmsg := fmt.Sprintf("balance too low.")
|
||||
log.Warnf("Balance of user %s too low", fromUserStr)
|
||||
return false, fmt.Errorf(errmsg)
|
||||
}
|
||||
|
||||
t.ToWallet = to.ID
|
||||
t.ToLNbitsID = to.ID
|
||||
|
||||
// generate invoice
|
||||
invoice, err := to.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Amount: int64(amount),
|
||||
Out: false,
|
||||
Memo: memo},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[Send] Error: Could not create invoice for user %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return false, err
|
||||
}
|
||||
t.Invoice = invoice
|
||||
// pay invoice
|
||||
_, err = from.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[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)
|
||||
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,24 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/nicksnyder/go-i18n/v2/i18n"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func Translate(ctx context.Context, MessgeID string) string {
|
||||
str, err := LoadPublicLocalizer(ctx).Localize(&i18n.LocalizeConfig{MessageID: MessgeID})
|
||||
if err != nil {
|
||||
log.Warnf("Error translating message %s: %s", MessgeID, err)
|
||||
}
|
||||
return str
|
||||
}
|
||||
|
||||
func TranslateUser(ctx context.Context, MessgeID string) string {
|
||||
str, err := LoadUserLocalizer(ctx).Localize(&i18n.LocalizeConfig{MessageID: MessgeID})
|
||||
if err != nil {
|
||||
log.Warnf("Error translating message %s: %s", MessgeID, err)
|
||||
}
|
||||
return str
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
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"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func SetUserState(user *lnbits.User, bot *TipBot, stateKey lnbits.UserStateKey, stateData string) {
|
||||
user.StateKey = stateKey
|
||||
user.StateData = stateData
|
||||
UpdateUserRecord(user, *bot)
|
||||
|
||||
}
|
||||
|
||||
func ResetUserState(user *lnbits.User, bot *TipBot) {
|
||||
user.ResetState()
|
||||
UpdateUserRecord(user, *bot)
|
||||
}
|
||||
|
||||
func GetUserStr(user *tb.User) string {
|
||||
userStr := fmt.Sprintf("@%s", user.Username)
|
||||
// if user does not have a username
|
||||
if len(userStr) < 2 && user.FirstName != "" {
|
||||
userStr = fmt.Sprintf("%s", user.FirstName)
|
||||
} else if len(userStr) < 2 {
|
||||
userStr = fmt.Sprintf("%d", user.ID)
|
||||
}
|
||||
return userStr
|
||||
}
|
||||
|
||||
func GetUserStrMd(user *tb.User) string {
|
||||
userStr := fmt.Sprintf("@%s", user.Username)
|
||||
// if user does not have a username
|
||||
if len(userStr) < 2 && user.FirstName != "" {
|
||||
userStr = fmt.Sprintf("[%s](tg://user?id=%d)", user.FirstName, user.ID)
|
||||
return userStr
|
||||
} else if len(userStr) < 2 {
|
||||
userStr = fmt.Sprintf("[%d](tg://user?id=%d)", user.ID, user.ID)
|
||||
return userStr
|
||||
} else {
|
||||
// escape only if user has a username
|
||||
return str.MarkdownEscape(userStr)
|
||||
}
|
||||
}
|
||||
|
||||
func appendUinqueUsersToSlice(slice []*tb.User, i *tb.User) []*tb.User {
|
||||
for _, ele := range slice {
|
||||
if ele.ID == i.ID {
|
||||
return slice
|
||||
}
|
||||
}
|
||||
return append(slice, i)
|
||||
}
|
||||
|
||||
func (bot *TipBot) GetUserBalanceCached(user *lnbits.User) (amount int64, err error) {
|
||||
u, err := bot.Cache.Get(fmt.Sprintf("%s_balance", user.Name))
|
||||
if err != nil {
|
||||
return bot.GetUserBalance(user)
|
||||
}
|
||||
cachedBalance := u.(int64)
|
||||
return cachedBalance, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
|
||||
wallet, err := bot.Client.Info(*user.Wallet)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[GetUserBalance] Error: Couldn't fetch user %s's info from LNbits: %s", GetUserStr(user.Telegram), err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
user.Wallet.Balance = wallet.Balance
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// msat to sat
|
||||
amount = int64(wallet.Balance) / 1000
|
||||
log.Debugf("[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},
|
||||
)
|
||||
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)
|
||||
err := bot.createWallet(user)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[CreateWalletForTelegramUser] Error: Could not create wallet for user %s", userStr)
|
||||
log.Errorln(errmsg)
|
||||
return user, err
|
||||
}
|
||||
// todo: remove this. we're doing this already in bot.createWallet().
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Printf("[CreateWalletForTelegramUser] Wallet created for user %s. ", userStr)
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) UserExists(user *tb.User) (*lnbits.User, bool) {
|
||||
lnbitUser, err := GetUser(user, *bot)
|
||||
if err != nil || errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, false
|
||||
}
|
||||
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
|
||||
}
|
||||
-95
@@ -1,95 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
invoiceEnterAmountMessage = "Did you enter an amount?"
|
||||
invoiceValidAmountMessage = "Did you enter a valid amount?"
|
||||
invoiceHelpText = "📖 Oops, that didn't work. %s\n\n" +
|
||||
"*Usage:* `/invoice <amount> [<memo>]`\n" +
|
||||
"*Example:* `/invoice 1000 Take this! 💸`"
|
||||
)
|
||||
|
||||
func helpInvoiceUsage(errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(invoiceHelpText, fmt.Sprintf("%s", errormsg))
|
||||
} else {
|
||||
return fmt.Sprintf(invoiceHelpText, "")
|
||||
}
|
||||
}
|
||||
|
||||
func (bot TipBot) invoiceHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
return
|
||||
}
|
||||
if len(strings.Split(m.Text, " ")) < 2 {
|
||||
bot.telegram.Send(m.Sender, helpInvoiceUsage(invoiceEnterAmountMessage))
|
||||
return
|
||||
}
|
||||
|
||||
user, err := GetUser(m.Sender, bot)
|
||||
userStr := GetUserStr(m.Sender)
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if amount > 0 {
|
||||
} else {
|
||||
bot.telegram.Send(m.Sender, helpInvoiceUsage(invoiceValidAmountMessage))
|
||||
return
|
||||
}
|
||||
|
||||
// check for memo in command
|
||||
memo := "Powered by @LightningTipBot"
|
||||
if len(strings.Split(m.Text, " ")) > 2 {
|
||||
memo = strings.SplitN(m.Text, " ", 3)[2]
|
||||
tag := " (@LightningTipBot)"
|
||||
memoMaxLen := 159 - len(tag)
|
||||
if len(memo) > memoMaxLen {
|
||||
memo = memo[:memoMaxLen-len(tag)]
|
||||
}
|
||||
memo = memo + tag
|
||||
}
|
||||
|
||||
log.Infof("[/invoice] Creating invoice for %s of %d sat.", userStr, amount)
|
||||
// generate invoice
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: int64(amount),
|
||||
Memo: memo,
|
||||
Webhook: Configuration.WebhookServer},
|
||||
*user.Wallet)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err)
|
||||
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)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// send the invoice data to user
|
||||
bot.telegram.Send(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
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
walletConnectMessage = "🔗 *Link your wallet*\n\n" +
|
||||
"⚠️ Never share the URL or the QR code with anyone or they will be able to access your funds.\n\n" +
|
||||
"- *BlueWallet:* Press *New wallet*, *Import wallet*, *Scan or import a file*, and scan the QR code.\n" +
|
||||
"- *Zeus:* Copy the URL below, press *Add a new node*, *Import* (the URL), *Save Node Config*."
|
||||
)
|
||||
|
||||
func (bot TipBot) lndhubHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
// reply only in private message
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
}
|
||||
// first check whether the user is initialized
|
||||
fromUser, err := GetUser(m.Sender, bot)
|
||||
if err != nil {
|
||||
log.Errorf("[/balance] Error: %s", err)
|
||||
return
|
||||
}
|
||||
bot.telegram.Send(m.Sender, walletConnectMessage)
|
||||
|
||||
lnbitsUrl := Configuration.LnbitsPublicUrl
|
||||
if !strings.HasSuffix(lnbitsUrl, "/") {
|
||||
lnbitsUrl = lnbitsUrl + "/"
|
||||
}
|
||||
lndhubUrl := fmt.Sprintf("lndhub://admin:%s@%slndhub/ext/", fromUser.Wallet.Adminkey, lnbitsUrl)
|
||||
|
||||
// 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)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// send the invoice data to user
|
||||
bot.telegram.Send(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
|
||||
}
|
||||
@@ -1,12 +1,26 @@
|
||||
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/price"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// setLogger will initialize the log format
|
||||
func setLogger() {
|
||||
log.SetLevel(log.InfoLevel)
|
||||
log.SetLevel(log.DebugLevel)
|
||||
customFormatter := new(log.TextFormatter)
|
||||
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
|
||||
customFormatter.FullTimestamp = true
|
||||
@@ -16,13 +30,43 @@ func setLogger() {
|
||||
func main() {
|
||||
// set logger
|
||||
setLogger()
|
||||
|
||||
defer withRecovery()
|
||||
bot := NewBot()
|
||||
price.NewPriceWatcher().Start()
|
||||
bot := telegram.NewBot()
|
||||
startApiServer(&bot)
|
||||
bot.Start()
|
||||
}
|
||||
func startApiServer(bot *telegram.TipBot) {
|
||||
// start internal webhook server
|
||||
webhook.NewServer(bot)
|
||||
// start external api server
|
||||
s := api.NewServer(internal.Configuration.Bot.LNURLServerUrl.Host)
|
||||
|
||||
// append lnurl handler functions
|
||||
lnUrl := lnurl.New(bot)
|
||||
s.AppendRoute("/.well-known/lnurlp/{username}", lnUrl.Handle, http.MethodGet)
|
||||
s.AppendRoute("/@{username}", lnUrl.Handle, http.MethodGet)
|
||||
|
||||
// append lndhub handler functions
|
||||
hub := lndhub.New(bot)
|
||||
s.AppendRoute(`/lndhub/ext/{.*}`, hub.Handle)
|
||||
s.AppendRoute(`/lndhub/ext`, hub.Handle)
|
||||
|
||||
// start internal admin server
|
||||
adminService := admin.New(bot)
|
||||
internalAdminServer := api.NewServer("0.0.0.0:6060")
|
||||
internalAdminServer.AppendRoute("/mutex", mutex.ServeHTTP)
|
||||
internalAdminServer.AppendRoute("/mutex/unlock/{id}", mutex.UnlockHTTP)
|
||||
internalAdminServer.AppendRoute("/admin/ban/{id}", adminService.BanUser)
|
||||
internalAdminServer.AppendRoute("/admin/unban/{id}", adminService.UnbanUser)
|
||||
internalAdminServer.PathPrefix("/debug/pprof/", http.DefaultServeMux)
|
||||
|
||||
}
|
||||
|
||||
func withRecovery() {
|
||||
if r := recover(); r != nil {
|
||||
log.Errorln("Recovered panic: ", r)
|
||||
debug.PrintStack()
|
||||
}
|
||||
}
|
||||
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
Message *tb.Message
|
||||
TipAmount int
|
||||
Ntips int
|
||||
LastTip time.Time
|
||||
Tippers []*tb.User
|
||||
}
|
||||
|
||||
const maxNamesInTipperMessage = 5
|
||||
|
||||
type messageOption func(m *Message)
|
||||
|
||||
func TipAmount(amount int) messageOption {
|
||||
return func(m *Message) {
|
||||
m.TipAmount = amount
|
||||
}
|
||||
}
|
||||
func Tips(nTips int) messageOption {
|
||||
return func(m *Message) {
|
||||
m.LastTip = time.Now()
|
||||
m.Ntips = nTips
|
||||
}
|
||||
}
|
||||
|
||||
func NewMessage(m *tb.Message, opts ...messageOption) *Message {
|
||||
msg := &Message{
|
||||
Message: m,
|
||||
Tippers: make([]*tb.User, 0),
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(msg)
|
||||
}
|
||||
return msg
|
||||
|
||||
}
|
||||
|
||||
func (x Message) Dispose(duration time.Duration, telegram *tb.Bot) {
|
||||
// do not delete messages from private chat
|
||||
if x.Message.Private() {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
time.Sleep(duration)
|
||||
err := telegram.Delete(x.Message)
|
||||
if err != nil {
|
||||
log.Println(err.Error())
|
||||
return
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func removeMessage(messages []*Message, s int) []*Message {
|
||||
if len(messages) == 1 {
|
||||
return make([]*Message, 0)
|
||||
}
|
||||
return append(messages[:s], messages[s+1:]...)
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
decodepay "github.com/fiatjaf/ln-decodepay"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
paymentCancelledMessage = "🚫 Payment cancelled."
|
||||
invoicePaidMessage = "⚡️ Invoice paid."
|
||||
invoicePrivateChatOnlyErrorMessage = "You can pay invoices only in the private chat with the bot."
|
||||
invalidInvoiceHelpMessage = "Did you enter a valid Lightning invoice?"
|
||||
invoiceNoAmountMessage = "🚫 Can't pay invoices without an amount."
|
||||
insufficientFundsMessage = "🚫 Insufficient funds. You have %d sat but you need at least %d sat."
|
||||
feeReserveMessage = "⚠️ Sending your entire balance might fail because of network fees. If it fails, try sending a bit less."
|
||||
invoicePaymentFailedMessage = "🚫 Failed to pay invoice: %s"
|
||||
confirmPayInvoiceMessage = "Do you want to pay this invoice?\n\n💸 Amount: %d sat"
|
||||
confirmPayAppendMemo = "\n✉️ %s"
|
||||
payHelpText = "📖 Oops, that didn't work. %s\n\n" +
|
||||
"*Usage:* `/pay <invoice>`\n" +
|
||||
"*Example:* `/pay lnbc20n1psscehd...`"
|
||||
)
|
||||
|
||||
func helpPayInvoiceUsage(errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(payHelpText, fmt.Sprintf("%s", errormsg))
|
||||
} else {
|
||||
return fmt.Sprintf(payHelpText, "")
|
||||
}
|
||||
}
|
||||
|
||||
// confirmPaymentHandler invoked on "/pay lnbc..." command
|
||||
func (bot TipBot) confirmPaymentHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
bot.telegram.Send(m.Sender, helpPayInvoiceUsage(invoicePrivateChatOnlyErrorMessage))
|
||||
return
|
||||
}
|
||||
if len(strings.Split(m.Text, " ")) < 2 {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
bot.telegram.Send(m.Sender, helpPayInvoiceUsage(""))
|
||||
return
|
||||
}
|
||||
user, err := GetUser(m.Sender, bot)
|
||||
if err != nil {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not GetUser: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
userStr := GetUserStr(m.Sender)
|
||||
paymentRequest, err := getArgumentFromCommand(m.Text, 1)
|
||||
if err != nil {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
bot.telegram.Send(m.Sender, helpPayInvoiceUsage(invalidInvoiceHelpMessage))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not getArgumentFromCommand: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
paymentRequest = strings.ToLower(paymentRequest)
|
||||
// get rid of the URI prefix
|
||||
paymentRequest = strings.TrimPrefix(paymentRequest, "lightning:")
|
||||
|
||||
// decode invoice
|
||||
bolt11, err := decodepay.Decodepay(paymentRequest)
|
||||
if err != nil {
|
||||
bot.telegram.Send(m.Sender, helpPayInvoiceUsage(invalidInvoiceHelpMessage))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
amount := int(bolt11.MSatoshi / 1000)
|
||||
|
||||
if amount <= 0 {
|
||||
bot.telegram.Send(m.Sender, invoiceNoAmountMessage)
|
||||
errmsg := fmt.Sprint("[/pay] Error: invoice without amount")
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// check user balance first
|
||||
balance, err := bot.GetUserBalance(m.Sender)
|
||||
if err != nil {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
if amount > balance {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf(insufficientFundsMessage, balance, amount))
|
||||
return
|
||||
}
|
||||
// send warning that the invoice might fail due to missing fee reserve
|
||||
if float64(amount) > float64(balance)*0.99 {
|
||||
bot.telegram.Send(m.Sender, feeReserveMessage)
|
||||
}
|
||||
|
||||
log.Printf("[/pay] User: %s, amount: %d sat.", userStr, amount)
|
||||
user.StateKey = lnbits.UserStateConfirmPayment
|
||||
user.StateData = paymentRequest
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
log.Printf("[UpdateUserRecord] User: %s Error: %s", userStr, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// // // create inline buttons
|
||||
paymentConfirmationMenu.Inline(paymentConfirmationMenu.Row(btnPay, btnCancelPay))
|
||||
confirmText := fmt.Sprintf(confirmPayInvoiceMessage, amount)
|
||||
if len(bolt11.Description) > 0 {
|
||||
confirmText = confirmText + fmt.Sprintf(confirmPayAppendMemo, MarkdownEscape(bolt11.Description))
|
||||
}
|
||||
bot.telegram.Send(m.Sender, confirmText, paymentConfirmationMenu)
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot TipBot) cancelPaymentHandler(c *tb.Callback) {
|
||||
// reset state immediately
|
||||
user, err := GetUser(c.Sender, bot)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
user.ResetState()
|
||||
err = UpdateUserRecord(user, bot)
|
||||
|
||||
bot.telegram.Delete(c.Message)
|
||||
_, err = bot.telegram.Send(c.Sender, paymentCancelledMessage)
|
||||
if err != nil {
|
||||
log.WithField("message", paymentCancelledMessage).WithField("user", c.Sender.ID).Printf("[Send] %s", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// payHandler when user clicked pay "X" on payment confirmation
|
||||
func (bot TipBot) payHandler(c *tb.Callback) {
|
||||
bot.telegram.Edit(c.Message, c.Message.Text, &tb.ReplyMarkup{})
|
||||
user, err := GetUser(c.Sender, bot)
|
||||
if err != nil {
|
||||
log.Printf("[GetUser] User: %d: %s", c.Sender.ID, err.Error())
|
||||
return
|
||||
}
|
||||
if user.StateKey == lnbits.UserStateConfirmPayment {
|
||||
invoiceString := user.StateData
|
||||
|
||||
// reset state immediatelly
|
||||
user.ResetState()
|
||||
err = UpdateUserRecord(user, bot)
|
||||
|
||||
userStr := GetUserStr(c.Sender)
|
||||
// pay invoice
|
||||
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoiceString}, *user.Wallet)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of user %s: %s", userStr, err)
|
||||
bot.telegram.Send(c.Sender, fmt.Sprintf(invoicePaymentFailedMessage, err))
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
bot.telegram.Send(c.Sender, invoicePaidMessage)
|
||||
log.Printf("[/pay] User %s paid invoice %s", userStr, invoice.PaymentHash)
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
"github.com/makiuchi-d/gozxing"
|
||||
"github.com/makiuchi-d/gozxing/qrcode"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
photoQrNotRecognizedMessage = "🚫 Could not regocognize a Lightning invoice. Try to center the QR code, crop the photo, or zoom in."
|
||||
photoInvoiceRecognizedMessage = "✅ Invoice:\n`%s`"
|
||||
)
|
||||
|
||||
// TryRecognizeInvoiceFromQrCode will try to read an invoice string from a qr code and invoke the payment handler.
|
||||
func TryRecognizeInvoiceFromQrCode(img image.Image) (*gozxing.Result, error) {
|
||||
// check for qr code
|
||||
bmp, _ := gozxing.NewBinaryBitmapFromImage(img)
|
||||
// decode image
|
||||
qrReader := qrcode.NewQRCodeReader()
|
||||
result, err := qrReader.Decode(bmp, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload := strings.ToLower(result.String())
|
||||
if lightning.IsInvoice(payload) {
|
||||
// create payment command payload
|
||||
// invoke payment confirmation handler
|
||||
return result, nil
|
||||
}
|
||||
return nil, fmt.Errorf("no codes found")
|
||||
}
|
||||
|
||||
// privatePhotoHandler is the handler function for every photo from a private chat that the bot receives
|
||||
func (bot TipBot) privatePhotoHandler(m *tb.Message) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return
|
||||
}
|
||||
if m.Photo == nil {
|
||||
return
|
||||
}
|
||||
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, "<Photo>")
|
||||
// get file reader closer from telegram api
|
||||
reader, err := bot.telegram.GetFile(m.Photo.MediaFile())
|
||||
if err != nil {
|
||||
log.Errorf("Getfile error: %v\n", err)
|
||||
return
|
||||
}
|
||||
// decode to jpeg image
|
||||
img, err := jpeg.Decode(reader)
|
||||
if err != nil {
|
||||
log.Errorf("image.Decode error: %v\n", err)
|
||||
return
|
||||
}
|
||||
data, err := TryRecognizeInvoiceFromQrCode(img)
|
||||
if err != nil {
|
||||
log.Errorf("tryRecognizeQrCodes error: %v\n", err)
|
||||
bot.telegram.Send(m.Sender, photoQrNotRecognizedMessage)
|
||||
return
|
||||
}
|
||||
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf(photoInvoiceRecognizedMessage, data.String()))
|
||||
|
||||
// invoke payment handler
|
||||
m.Text = fmt.Sprintf("/pay %s", data.String())
|
||||
bot.confirmPaymentHandler(m)
|
||||
}
|
||||
@@ -1,18 +1,36 @@
|
||||
package lightning
|
||||
|
||||
import (
|
||||
"net/mail"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// IsInvoice is used to check if a string matches lnbc invoide pattern.
|
||||
// todo -- probably should add regex and validate length
|
||||
func IsInvoice(invoice string) bool {
|
||||
func IsInvoice(message string) bool {
|
||||
message = strings.ToLower(message)
|
||||
// invoice string must start with lnbc or lightning:lnbc
|
||||
if strings.HasPrefix(invoice, "lnbc") || strings.HasPrefix(invoice, "lightning:lnbc") {
|
||||
if strings.HasPrefix(message, "lnbc") || strings.HasPrefix(message, "lightning:lnbc") {
|
||||
// invoice string must be a single word
|
||||
if !strings.Contains(invoice, " ") {
|
||||
if !strings.Contains(message, " ") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func IsLnurl(message string) bool {
|
||||
message = strings.ToLower(message)
|
||||
if strings.HasPrefix(message, "lnurl") || strings.HasPrefix(message, "lightning:lnurl") {
|
||||
// string must be a single word
|
||||
if !strings.Contains(message, " ") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func IsLightningAddress(address string) bool {
|
||||
_, err := mail.ParseAddress(address)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 172 KiB After Width: | Height: | Size: 107 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 39 KiB |
@@ -1,278 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
sendValidAmountMessage = "Did you enter a valid amount?"
|
||||
sendUserNotFoundMessage = "User %s could not be found. You can /send only to Telegram tags like @%s."
|
||||
sendIsNotAUsser = "🚫 %s is not a username. You can /send only to Telegram tags like @%s."
|
||||
sendUserHasNoWalletMessage = "🚫 User %s hasn't created a wallet yet."
|
||||
sendSentMessage = "💸 %d sat sent to %s."
|
||||
sendReceivedMessage = "🏅 %s has sent you %d sat."
|
||||
sendErrorMessage = "🚫 Transaction failed: %s"
|
||||
confirmSendInvoiceMessage = "Do you want to pay to %s?\n\n💸 Amount: %d sat"
|
||||
confirmSendAppendMemo = "\n✉️ %s"
|
||||
sendCancelledMessage = "🚫 Send cancelled."
|
||||
errorTryLaterMessage = "🚫 Internal error. Please try again later.."
|
||||
sendHelpText = "📖 Oops, that didn't work. %s\n\n" +
|
||||
"*Usage:* `/send <amount> <user> [<memo>]`\n" +
|
||||
"*Example:* `/send 1000 @LightningTipBot I just like the bot ❤️`"
|
||||
)
|
||||
|
||||
func helpSendUsage(errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(sendHelpText, fmt.Sprintf("%s", errormsg))
|
||||
} else {
|
||||
return fmt.Sprintf(sendHelpText, "")
|
||||
}
|
||||
}
|
||||
|
||||
func SendCheckSyntax(m *tb.Message) (bool, string) {
|
||||
arguments := strings.Split(m.Text, " ")
|
||||
if len(arguments) < 2 {
|
||||
return false, "Did you enter an amount and a recipient?"
|
||||
}
|
||||
if len(arguments) < 3 {
|
||||
return false, "Did you enter a recipient?"
|
||||
}
|
||||
if !strings.HasPrefix(arguments[0], "/send") {
|
||||
return false, "Did you enter a valid command?"
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
|
||||
// confirmPaymentHandler invoked on "/send 123 @user" command
|
||||
func (bot *TipBot) confirmSendHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
// If the send is a reply, then trigger /tip handler
|
||||
if m.IsReply() {
|
||||
bot.tipHandler(m)
|
||||
return
|
||||
}
|
||||
|
||||
if ok, err := SendCheckSyntax(m); !ok {
|
||||
bot.telegram.Send(m.Sender, helpSendUsage(err))
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
return
|
||||
}
|
||||
|
||||
// get send amount
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if err != nil || amount < 1 {
|
||||
errmsg := fmt.Sprintf("[/send] Error: Send amount not valid.")
|
||||
log.Errorln(errmsg)
|
||||
// immediately delete if the amount is bullshit
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
bot.telegram.Send(m.Sender, helpSendUsage(sendValidAmountMessage))
|
||||
return
|
||||
}
|
||||
|
||||
// SEND COMMAND IS VALID
|
||||
|
||||
// check for memo in command
|
||||
sendMemo := ""
|
||||
if len(strings.Split(m.Text, " ")) > 3 {
|
||||
sendMemo = strings.SplitN(m.Text, " ", 4)[3]
|
||||
if len(sendMemo) > 200 {
|
||||
sendMemo = sendMemo[:200]
|
||||
sendMemo = sendMemo + "..."
|
||||
}
|
||||
}
|
||||
|
||||
if len(m.Entities) < 2 {
|
||||
arg, err := getArgumentFromCommand(m.Text, 2)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
arg = MarkdownEscape(arg)
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
errmsg := fmt.Sprintf("Error: User %s could not be found", arg)
|
||||
bot.telegram.Send(m.Sender, helpSendUsage(fmt.Sprintf(sendUserNotFoundMessage, arg, arg)))
|
||||
log.Errorln(errmsg)
|
||||
|
||||
return
|
||||
}
|
||||
if m.Entities[1].Type != "mention" {
|
||||
arg, err := getArgumentFromCommand(m.Text, 2)
|
||||
if err != nil {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
arg = MarkdownEscape(arg)
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
errmsg := fmt.Sprintf("Error: %s is not a user", arg)
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf(sendIsNotAUsser, arg, arg))
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
toUserStrMention := m.Text[m.Entities[1].Offset : m.Entities[1].Offset+m.Entities[1].Length]
|
||||
toUserStrWithoutAt := strings.TrimPrefix(toUserStrMention, "@")
|
||||
|
||||
err = bot.parseCmdDonHandler(m)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
toUserDb := &lnbits.User{}
|
||||
tx := bot.database.Where("telegram_username = ?", toUserStrWithoutAt).First(toUserDb)
|
||||
if tx.Error != nil || toUserDb.Wallet == nil || toUserDb.Initialized == false {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
errmsg := fmt.Sprintf(sendUserHasNoWalletMessage, MarkdownEscape(toUserStrMention))
|
||||
log.Println("[/send] Error: " + errmsg)
|
||||
bot.telegram.Send(m.Sender, errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// string that holds all information about the send payment
|
||||
sendData := strconv.Itoa(toUserDb.Telegram.ID) + "|" + toUserStrWithoutAt + "|" +
|
||||
strconv.Itoa(amount)
|
||||
if len(sendMemo) > 0 {
|
||||
sendData = sendData + "|" + sendMemo
|
||||
}
|
||||
|
||||
// save the send data to the database
|
||||
log.Debug(sendData)
|
||||
user, err := GetUser(m.Sender, *bot)
|
||||
if err != nil {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
log.Printf("[/send] Error: %s\n", err.Error())
|
||||
bot.telegram.Send(m.Sender, fmt.Sprint(errorTryLaterMessage))
|
||||
return
|
||||
}
|
||||
user.StateKey = lnbits.UserStateConfirmSend
|
||||
user.StateData = sendData
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
if err != nil {
|
||||
log.Printf("[UpdateUserRecord] User: %s Error: %s", GetUserStr(m.Sender), err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
sendConfirmationMenu.Inline(sendConfirmationMenu.Row(btnSend, btnCancelSend))
|
||||
confirmText := fmt.Sprintf(confirmSendInvoiceMessage, MarkdownEscape(toUserStrMention), amount)
|
||||
if len(sendMemo) > 0 {
|
||||
confirmText = confirmText + fmt.Sprintf(confirmSendAppendMemo, MarkdownEscape(sendMemo))
|
||||
}
|
||||
_, err = bot.telegram.Send(m.Sender, confirmText, sendConfirmationMenu)
|
||||
if err != nil {
|
||||
log.Error("[confirmSendHandler]" + err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot *TipBot) cancelSendHandler(c *tb.Callback) {
|
||||
// reset state immediately
|
||||
user, err := GetUser(c.Sender, *bot)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
user.ResetState()
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
// delete the confirmation message
|
||||
err = bot.telegram.Delete(c.Message)
|
||||
if err != nil {
|
||||
log.Errorln("[cancelSendHandler] " + err.Error())
|
||||
}
|
||||
// notify the user
|
||||
_, err = bot.telegram.Send(c.Sender, sendCancelledMessage)
|
||||
if err != nil {
|
||||
log.WithField("message", sendCancelledMessage).WithField("user", c.Sender.ID).Printf("[Send] %s", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// sendHandler invoked when user clicked send on payment confirmation
|
||||
func (bot *TipBot) sendHandler(c *tb.Callback) {
|
||||
// remove buttons from confirmation message
|
||||
_, err := bot.telegram.Edit(c.Message, MarkdownEscape(c.Message.Text), &tb.ReplyMarkup{})
|
||||
if err != nil {
|
||||
log.Errorln("[sendHandler] " + err.Error())
|
||||
}
|
||||
// decode callback data
|
||||
// log.Debug("[sendHandler] Callback: %s", c.Data)
|
||||
user, err := GetUser(c.Sender, *bot)
|
||||
if err != nil {
|
||||
log.Printf("[GetUser] User: %d: %s", c.Sender.ID, err.Error())
|
||||
return
|
||||
}
|
||||
if user.StateKey != lnbits.UserStateConfirmSend {
|
||||
log.Errorf("[sendHandler] User StateKey does not match! User: %d: StateKey: %d", c.Sender.ID, user.StateKey)
|
||||
return
|
||||
}
|
||||
|
||||
// decode StateData in which we have information about the send payment
|
||||
splits := strings.Split(user.StateData, "|")
|
||||
if len(splits) < 3 {
|
||||
log.Error("[sendHandler] Not enough arguments in callback data")
|
||||
log.Errorf("user.StateData: %s", user.StateData)
|
||||
return
|
||||
}
|
||||
toId, err := strconv.Atoi(splits[0])
|
||||
if err != nil {
|
||||
log.Errorln("[sendHandler] " + err.Error())
|
||||
}
|
||||
toUserStrWithoutAt := splits[1]
|
||||
amount, err := strconv.Atoi(splits[2])
|
||||
if err != nil {
|
||||
log.Errorln("[sendHandler] " + err.Error())
|
||||
}
|
||||
sendMemo := ""
|
||||
if len(splits) > 3 {
|
||||
sendMemo = strings.Join(splits[3:], "|")
|
||||
}
|
||||
|
||||
// reset state
|
||||
user.ResetState()
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
// we can now get the wallets of both users
|
||||
to := &tb.User{ID: toId, Username: toUserStrWithoutAt}
|
||||
from := c.Sender
|
||||
toUserStrMd := GetUserStrMd(to)
|
||||
fromUserStrMd := GetUserStrMd(from)
|
||||
toUserStr := GetUserStr(to)
|
||||
fromUserStr := GetUserStr(from)
|
||||
|
||||
transactionMemo := fmt.Sprintf("Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
t := NewTransaction(bot, from, to, amount, TransactionType("send"))
|
||||
t.Memo = transactionMemo
|
||||
|
||||
success, err := t.Send()
|
||||
if !success || err != nil {
|
||||
// NewMessage(m).Dispose(0, bot.telegram)
|
||||
bot.telegram.Send(c.Sender, fmt.Sprintf(sendErrorMessage, err))
|
||||
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
bot.telegram.Send(from, fmt.Sprintf(sendSentMessage, amount, toUserStrMd))
|
||||
bot.telegram.Send(to, fmt.Sprintf(sendReceivedMessage, fromUserStrMd, amount))
|
||||
// send memo if it was present
|
||||
if len(sendMemo) > 0 {
|
||||
bot.telegram.Send(to, fmt.Sprintf("✉️ %s", MarkdownEscape(sendMemo)))
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
startSettingWalletMessage = "🧮 Setting up your wallet..."
|
||||
startWalletReadyMessage = "✅ *Your wallet is ready.*"
|
||||
startWalletErrorMessage = "🚫 Error initializing your wallet. Try again later."
|
||||
startNoUsernameMessage = "☝️ It looks like you don't have a Telegram @username yet. That's ok, you don't need one to use this bot. However, to make better use of your wallet, set up a username in the [Telegram settings](https://telegram.org/faq#q-what-are-usernames-how-do-i-get-one). Then, enter /balance so the bot can update its record of you."
|
||||
)
|
||||
|
||||
func (bot TipBot) startHandler(m *tb.Message) {
|
||||
if !m.Private() {
|
||||
return
|
||||
}
|
||||
// ATTENTION: DO NOT CALL ANY HANDLER BEFORE THE WALLET IS CREATED
|
||||
// WILL RESULT IN AN ENDLESS LOOP OTHERWISE
|
||||
// bot.helpHandler(m)
|
||||
bot.telegram.Send(m.Sender, helpMessage, tb.NoPreview)
|
||||
log.Printf("[/start] User: %s (%d)\n", m.Sender.Username, m.Sender.ID)
|
||||
walletCreationMsg, err := bot.telegram.Send(m.Sender, startSettingWalletMessage)
|
||||
err = bot.initWallet(m.Sender)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[startHandler] Error with initWallet: %s", err.Error()))
|
||||
bot.telegram.Edit(walletCreationMsg, startWalletErrorMessage)
|
||||
return
|
||||
}
|
||||
bot.telegram.Edit(walletCreationMsg, startWalletReadyMessage)
|
||||
bot.balanceHandler(m)
|
||||
|
||||
// send the user a warning about the fact that they need to set a username
|
||||
if len(m.Sender.Username) == 0 {
|
||||
bot.telegram.Send(m.Sender, startNoUsernameMessage, tb.NoPreview)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) initWallet(tguser *tb.User) error {
|
||||
user, err := GetUser(tguser, bot)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
u := &lnbits.User{Telegram: tguser}
|
||||
err = bot.createWallet(u)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
u.Initialized = true
|
||||
err = UpdateUserRecord(u, bot)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
|
||||
return err
|
||||
}
|
||||
} else if !user.Initialized {
|
||||
// update all tip tooltips (with the "initialize me" message) that this user might have received before
|
||||
tipTooltipInitializedHandler(user.Telegram, bot)
|
||||
user.Initialized = true
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
|
||||
return err
|
||||
}
|
||||
} else if user.Initialized {
|
||||
// wallet is already initialized
|
||||
return nil
|
||||
} else {
|
||||
err = fmt.Errorf("could not initialize wallet")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (bot TipBot) createWallet(user *lnbits.User) error {
|
||||
UserStr := GetUserStr(user.Telegram)
|
||||
u, err := bot.client.CreateUserWithInitialWallet(strconv.Itoa(user.Telegram.ID),
|
||||
fmt.Sprintf("%d (%s)", user.Telegram.ID, UserStr),
|
||||
Configuration.AdminKey,
|
||||
UserStr)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err)
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
user.Wallet = &lnbits.Wallet{Client: bot.client}
|
||||
user.ID = u.ID
|
||||
user.Name = u.Name
|
||||
wallet, err := user.Wallet.Wallets(*user)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err)
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
user.Wallet = &wallet[0]
|
||||
user.Wallet.Client = bot.client
|
||||
user.Initialized = false
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err)
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
initWalletMessage = "You don't have a wallet yet. Enter */start*"
|
||||
)
|
||||
|
||||
func (bot TipBot) anyTextHandler(m *tb.Message) {
|
||||
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return
|
||||
}
|
||||
|
||||
// check if user is in database, if not, initialize wallet
|
||||
if !bot.UserHasWallet(m.Sender) {
|
||||
bot.startHandler(m)
|
||||
return
|
||||
}
|
||||
|
||||
// could be an invoice
|
||||
invoiceString := strings.ToLower(m.Text)
|
||||
if lightning.IsInvoice(invoiceString) {
|
||||
m.Text = "/pay " + invoiceString
|
||||
bot.confirmPaymentHandler(m)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
tipDidYouReplyMessage = "Did you reply to a message to tip? To reply to any message, right-click -> Reply on your computer or swipe the message on your phone. If you want to send directly to another Telegram user's wallet, use the /send command."
|
||||
tipEnterAmountMessage = "Did you enter an amount?"
|
||||
tipValidAmountMessage = "Did you enter a valid amount?"
|
||||
tipYourselfMessage = "📖 You can't tip yourself."
|
||||
tipSentMessage = "💸 %d sat sent to %s."
|
||||
tipReceivedMessage = "🏅 %s has tipped you %d sat."
|
||||
tipErrorMessage = "🚫 Transaction failed: %s"
|
||||
tipHelpText = "📖 Oops, that didn't work. %s\n\n" +
|
||||
"*Usage:* `/tip <amount> [<memo>]`\n" +
|
||||
"*Example:* `/tip 1000 Dank meme!`"
|
||||
)
|
||||
|
||||
func helpTipUsage(errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(tipHelpText, fmt.Sprintf("%s", errormsg))
|
||||
} else {
|
||||
return fmt.Sprintf(tipHelpText, "")
|
||||
}
|
||||
}
|
||||
|
||||
func TipCheckSyntax(m *tb.Message) (bool, string) {
|
||||
arguments := strings.Split(m.Text, " ")
|
||||
if len(arguments) < 2 {
|
||||
return false, tipEnterAmountMessage
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
|
||||
func (bot *TipBot) tipHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
// only if message is a reply
|
||||
if !m.IsReply() {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
bot.telegram.Send(m.Sender, helpTipUsage(fmt.Sprintf(tipDidYouReplyMessage)))
|
||||
return
|
||||
}
|
||||
|
||||
if ok, err := TipCheckSyntax(m); !ok {
|
||||
bot.telegram.Send(m.Sender, helpTipUsage(err))
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
return
|
||||
}
|
||||
|
||||
// get tip amount
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if err != nil || amount < 1 {
|
||||
errmsg := fmt.Sprintf("[/tip] Error: Tip amount not valid.")
|
||||
// immediately delete if the amount is bullshit
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
bot.telegram.Send(m.Sender, helpTipUsage(tipValidAmountMessage))
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
err = bot.parseCmdDonHandler(m)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
// TIP COMMAND IS VALID
|
||||
|
||||
to := m.ReplyTo.Sender
|
||||
from := m.Sender
|
||||
|
||||
if from.ID == to.ID {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
bot.telegram.Send(m.Sender, tipYourselfMessage)
|
||||
return
|
||||
}
|
||||
|
||||
toUserStrMd := GetUserStrMd(m.ReplyTo.Sender)
|
||||
fromUserStrMd := GetUserStrMd(from)
|
||||
toUserStr := GetUserStr(m.ReplyTo.Sender)
|
||||
fromUserStr := GetUserStr(from)
|
||||
|
||||
if !bot.UserHasWallet(to) {
|
||||
log.Infof("[/tip] User %s has no wallet.", toUserStr)
|
||||
err = bot.CreateWalletForTelegramUser(to)
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[/tip] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// check for memo in command
|
||||
tipMemo := ""
|
||||
if len(strings.Split(m.Text, " ")) > 2 {
|
||||
tipMemo = strings.SplitN(m.Text, " ", 3)[2]
|
||||
if len(tipMemo) > 200 {
|
||||
tipMemo = tipMemo[:200]
|
||||
tipMemo = tipMemo + "..."
|
||||
}
|
||||
}
|
||||
|
||||
// todo: user new get username function to get userStrings
|
||||
transactionMemo := fmt.Sprintf("Tip from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
|
||||
t := NewTransaction(bot, from, to, amount, TransactionType("tip"), TransactionChat(m.Chat))
|
||||
t.Memo = transactionMemo
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
if err != nil {
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf(tipErrorMessage, err))
|
||||
} else {
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf(tipErrorMessage, "please try again later"))
|
||||
}
|
||||
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err)
|
||||
log.Errorln(errMsg)
|
||||
return
|
||||
}
|
||||
|
||||
// delete the tip message after a few seconds, this is default behaviour
|
||||
NewMessage(m).Dispose(time.Second*time.Duration(Configuration.MessageDisposeDuration), bot.telegram)
|
||||
|
||||
// update tooltip if necessary
|
||||
messageHasTip := tipTooltipHandler(m, from, bot, amount, bot.UserInitializedWallet(to))
|
||||
|
||||
log.Infof("[tip] %d sat from %s to %s", amount, fromUserStr, toUserStr)
|
||||
|
||||
// notify users
|
||||
_, err = bot.telegram.Send(from, fmt.Sprintf(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 {
|
||||
bot.telegram.Forward(to, m.ReplyTo, tb.Silent)
|
||||
}
|
||||
bot.telegram.Send(to, fmt.Sprintf(tipReceivedMessage, fromUserStrMd, amount))
|
||||
|
||||
if len(tipMemo) > 0 {
|
||||
bot.telegram.Send(to, fmt.Sprintf("✉️ %s", MarkdownEscape(tipMemo)))
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
-149
@@ -1,149 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot *TipBot) cleanupTipsFromMemory() {
|
||||
go func() {
|
||||
defer withRecovery()
|
||||
for {
|
||||
for userId, userTips := range bot.tips {
|
||||
for i, tip := range userTips {
|
||||
if time.Now().Sub(tip.LastTip) > (time.Hour*24)*7 {
|
||||
userTips = removeMessage(userTips, i)
|
||||
err := bot.telegram.Delete(tip.Message)
|
||||
if err != nil {
|
||||
log.WithField("error", err.Error()).Error("could not delete tip tool tip")
|
||||
}
|
||||
bot.tips[userId] = userTips
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
time.Sleep(time.Hour)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// updateToolTip updates existing tip tool tip in telegram
|
||||
func (x *Message) updateTooltip(bot *TipBot, user *tb.User, amount int, notInitializedWallet bool) {
|
||||
x.TipAmount += amount
|
||||
x.Ntips += 1
|
||||
x.Tippers = appendUinqueUsersToSlice(x.Tippers, user)
|
||||
x.LastTip = time.Now()
|
||||
userTips := bot.tips[x.Message.ReplyTo.Sender.ID]
|
||||
for _, tip := range userTips {
|
||||
if tip.Message.ReplyTo.Sender.ID == x.Message.ReplyTo.Sender.ID {
|
||||
err := x.editTooltip(bot, notInitializedWallet)
|
||||
if err != nil {
|
||||
log.Printf("[updateTooltip] could not edit tooltip: %s", err.Error())
|
||||
continue
|
||||
}
|
||||
tip = x
|
||||
}
|
||||
}
|
||||
bot.tips[x.Message.ReplyTo.Sender.ID] = userTips
|
||||
}
|
||||
func (x *Message) editTooltip(bot *TipBot, notInitializedWallet bool) error {
|
||||
tipToolTip := x.getTooltipMessage(GetUserStrMd(bot.telegram.Me), notInitializedWallet)
|
||||
m, err := bot.telegram.Edit(x.Message, tipToolTip)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Message.Text = m.Text
|
||||
return nil
|
||||
}
|
||||
func tipTooltipInitializedHandler(user *tb.User, bot TipBot) {
|
||||
for _, tip := range bot.tips[user.ID] {
|
||||
if tip.Message.ReplyTo.Sender.ID == user.ID {
|
||||
err := tip.editTooltip(&bot, false)
|
||||
if err != nil {
|
||||
log.Printf("[tipTooltipInitializedHandler] could not edit tooltip: %s", err.Error())
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// getTippersString joins all tippers username or telegram id's as mentions (@username or [inline mention of a user](tg://user?id=123456789))
|
||||
func getTippersString(tippers []*tb.User) string {
|
||||
var tippersStr string
|
||||
for _, uniqueUser := range tippers {
|
||||
userStr := GetUserStrMd(uniqueUser)
|
||||
tippersStr += fmt.Sprintf("%s, ", userStr)
|
||||
}
|
||||
// get rid of the trailing comma
|
||||
if len(tippersStr) > 2 {
|
||||
tippersStr = tippersStr[:len(tippersStr)-2]
|
||||
}
|
||||
tippersSlice := strings.Split(tippersStr, " ")
|
||||
// crop the message to the max length
|
||||
if len(tippersSlice) > maxNamesInTipperMessage {
|
||||
// tippersStr = tippersStr[:50]
|
||||
tippersStr = strings.Join(tippersSlice[:maxNamesInTipperMessage], " ")
|
||||
tippersStr = tippersStr + " ... and others"
|
||||
}
|
||||
return tippersStr
|
||||
}
|
||||
|
||||
// getTooltipMessage will return the full tip tool tip
|
||||
func (x Message) getTooltipMessage(botUserName string, notInitializedWallet bool) string {
|
||||
tippersStr := getTippersString(x.Tippers)
|
||||
tipToolTipMessage := fmt.Sprintf("🏅 %d sat", x.TipAmount)
|
||||
if len(x.Tippers) > 1 {
|
||||
tipToolTipMessage = fmt.Sprintf("%s (%d tips by %s)", tipToolTipMessage, x.Ntips, tippersStr)
|
||||
} else {
|
||||
tipToolTipMessage = fmt.Sprintf("%s (by %s)", tipToolTipMessage, tippersStr)
|
||||
}
|
||||
|
||||
if notInitializedWallet {
|
||||
tipToolTipMessage = tipToolTipMessage + fmt.Sprintf("\n🗑 Chat with %s to manage your wallet.", botUserName)
|
||||
}
|
||||
return tipToolTipMessage
|
||||
}
|
||||
|
||||
// tipTooltipExists checks if this tip is already known
|
||||
func tipTooltipExists(m *tb.Message, bot *TipBot) (bool, *Message) {
|
||||
for _, tip := range bot.tips[m.ReplyTo.Sender.ID] {
|
||||
if tip.Message.ReplyTo != nil && m.ReplyTo != nil {
|
||||
if tip.Message.ReplyTo.ID == m.ReplyTo.ID {
|
||||
return true, tip
|
||||
}
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// tipTooltipHandler function to update the tooltip below a tipped message. either updates or creates initial tip tool tip
|
||||
func tipTooltipHandler(m *tb.Message, user *tb.User, bot *TipBot, amount int, notInitializedWallet bool) 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!
|
||||
ok, tipMessage := tipTooltipExists(m, bot)
|
||||
if ok {
|
||||
// update the tooltip with new tippers
|
||||
tipMessage.updateTooltip(bot, user, amount, notInitializedWallet)
|
||||
} else {
|
||||
tipmsg := fmt.Sprintf("🏅 %d sat", amount)
|
||||
userStr := GetUserStrMd(user)
|
||||
tipmsg = fmt.Sprintf("%s (by %s)", tipmsg, userStr)
|
||||
|
||||
if notInitializedWallet {
|
||||
tipmsg = tipmsg + fmt.Sprintf("\n🗑 Chat with %s to manage your wallet.", GetUserStrMd(bot.telegram.Me))
|
||||
}
|
||||
msg, err := bot.telegram.Reply(m.ReplyTo, tipmsg, tb.Silent)
|
||||
if err != nil {
|
||||
print(err)
|
||||
}
|
||||
message := NewMessage(msg, TipAmount(amount), Tips(1))
|
||||
message.Tippers = appendUinqueUsersToSlice(message.Tippers, user)
|
||||
bot.tips[m.ReplyTo.Sender.ID] = append(bot.tips[m.ReplyTo.Sender.ID], message)
|
||||
}
|
||||
// first call will return false, every following call will return true
|
||||
return ok
|
||||
}
|
||||
-153
@@ -1,153 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type Transaction struct {
|
||||
ID uint `gorm:"primarykey"`
|
||||
Time time.Time `json:"time"`
|
||||
Bot *TipBot `gorm:"-"`
|
||||
From *tb.User `json:"from" gorm:"-"`
|
||||
To *tb.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)
|
||||
|
||||
func TransactionChat(chat *tb.Chat) transactionOption {
|
||||
return func(t *Transaction) {
|
||||
t.ChatID = chat.ID
|
||||
t.ChatName = chat.Title
|
||||
}
|
||||
}
|
||||
|
||||
func TransactionType(transactionType string) transactionOption {
|
||||
return func(t *Transaction) {
|
||||
t.Type = transactionType
|
||||
}
|
||||
}
|
||||
|
||||
func NewTransaction(bot *TipBot, from *tb.User, to *tb.User, amount int, opts ...transactionOption) *Transaction {
|
||||
t := &Transaction{
|
||||
Bot: bot,
|
||||
From: from,
|
||||
To: to,
|
||||
FromUser: GetUserStr(from),
|
||||
ToUser: GetUserStr(to),
|
||||
FromId: from.ID,
|
||||
ToId: to.ID,
|
||||
Amount: amount,
|
||||
Memo: "Powered by @LightningTipBot",
|
||||
Time: time.Now(),
|
||||
Success: false,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(t)
|
||||
}
|
||||
return t
|
||||
|
||||
}
|
||||
|
||||
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)
|
||||
log.Errorln(errMsg)
|
||||
}
|
||||
|
||||
return success, err
|
||||
}
|
||||
|
||||
func (t *Transaction) SendTransaction(bot *TipBot, from *tb.User, to *tb.User, amount int, memo string) (bool, error) {
|
||||
fromUserStr := GetUserStr(from)
|
||||
toUserStr := GetUserStr(to)
|
||||
|
||||
// from := m.Sender
|
||||
fromUser, err := GetUser(from, *bot)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[SendTransaction] Error: Could not get user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return false, err
|
||||
}
|
||||
t.FromWallet = fromUser.Wallet.ID
|
||||
t.FromLNbitsID = fromUser.ID
|
||||
// check if fromUser has balance
|
||||
balance, err := bot.GetUserBalance(from)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[SendTransaction] Error: Could not get balance of user %s", fromUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return false, err
|
||||
}
|
||||
// check if fromUser has balance
|
||||
if balance < amount {
|
||||
errmsg := fmt.Sprintf("[SendTransaction] Error: User %s has not enough balance", fromUserStr)
|
||||
bot.telegram.Send(from, fmt.Sprintf("🚫 Your balance is too low for that."))
|
||||
log.Errorln(errmsg)
|
||||
return false, fmt.Errorf(errmsg)
|
||||
}
|
||||
|
||||
toUser, err := GetUser(to, *bot)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[SendTransaction] Error: ToUser %s not found: %s", toUserStr, err)
|
||||
log.Errorln(errmsg)
|
||||
return false, err
|
||||
}
|
||||
t.ToWallet = toUser.Wallet.ID
|
||||
t.ToLNbitsID = toUser.ID
|
||||
|
||||
// generate invoice
|
||||
invoice, err := toUser.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Amount: int64(amount),
|
||||
Out: false,
|
||||
Memo: memo},
|
||||
*toUser.Wallet)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[SendTransaction] Error: Could not create invoice for user %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
return false, err
|
||||
}
|
||||
// pay invoice
|
||||
_, err = fromUser.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, *fromUser.Wallet)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[SendTransaction] Error: Payment from %s to %s of %d sat failed", fromUserStr, toUserStr, amount)
|
||||
log.Errorln(errmsg)
|
||||
return false, err
|
||||
}
|
||||
return true, err
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
# Translation guide
|
||||
|
||||
Thank you for helping to translate this bot into many different languages. If you chose to translate this bot, please try to test every possible case that you can think of. As time passes, new features will be added and your translation could become out of date. It would be great, if you could update your language's translation if you notice any weird changes.
|
||||
|
||||
## Quick and dirty summary
|
||||
* Duplicate `en.toml` to your localization and edit string by string.
|
||||
* Do not translate commands in the text! I.e. `/balance` stays `/balance`.
|
||||
* Pay attention to every single `"""` and `%s` or `%d`.
|
||||
* Your end result should have exactly the same number of lines as `en.toml`.
|
||||
* Start sentences with `C`apital letters, end them with a full stop`.`
|
||||
|
||||
## General
|
||||
* The bot checks the language settings of each Telegram user and translate the interaction with the user (private chats, **inline commands?**) to the user's language, if a translation is available. Otherwise, it will default to english. All messages in groups will be english. If the user does not have a language setting, it will default to english.
|
||||
* For now, all `/commands` are in english. That means that all `/command` references in the help messages should remain english for now. We plan to implement localized commands, which is why you will find the strings in the translation files. Please chose simple, single-worded, lower-case, for the command translations.
|
||||
* Please use a spell checker, like Google Docs to check your final translation. Thanks :)
|
||||
|
||||
## Language
|
||||
* Please use a "kind" and "playful" tone in your translations. We do not have to be very dry and technical in tone. Please use a respectful language.
|
||||
* Please remember who the prototypical user is: a non-technical fruit-selling lady in Brazil that wants to sell Mangos for Satoshis.
|
||||
|
||||
## Standards
|
||||
* Please "fork" your translation from the english translation file `en.toml`. Simply copy the file, rename it to your language code (look it up on Google if you're unsure) and start editing :)
|
||||
* Please use only "sat" as a denominator for amounts, do not use the plural form "sats".
|
||||
* Please choose an appropriate expression for "Amount" and keep it across the entire translation.
|
||||
* Please reuse all Emojis in the same location and order as the original text.
|
||||
* Do not add line breaks. All translations should have the same number of lines.
|
||||
* Please use english words for Bitcoin- and Lightning-native concepts like "Lightning", "Wallet", "Invoice", "Tip", and other technical terms like "Log", "Bot", etc. **IF** your language does not have a widely-used and recognized alternative for it. If most software in your language uses another word instead of "Wallet" for example, then we should also use that.
|
||||
* For fixed english terms like "Tip" I recommend using the english version and giving a translation in parenthesis like "... Tips (*kleine Beträge*) senden kann". The text in *italic* is the next best translation of "Tips"
|
||||
|
||||
|
||||
## Technical
|
||||
* Every string should be wrapped in three quotes `"""`
|
||||
* Strings can span over multiple lines.
|
||||
* Every string variable found in the original english language file should be translated. If a specific string is missing in a translation, the english version will be used for that particular string.
|
||||
* Every language has their own translation file. The file for english is `en.toml`.
|
||||
|
||||
* Headings to many sections are **bold** starting and ending with asterix `*`. Italic starts and ends with an underscore `_`.
|
||||
* Command examples are in `code format` starting end ending with ``` ` ```
|
||||
|
||||
## Pleaceholders
|
||||
* Symbols like `%s`, `%d`, `%f` are meant as placeholders for other bits of text, numbers, floats. Please reuse them in every string you translate.
|
||||
* Please do not change the order of the placeholders in your translation. It would break things.
|
||||
* Please do not use modifiers for **bold**, *italic*, and others around the placeholders. We are using MarkdownV1 and it would break things. Do not do `_%s_` for example.
|
||||
|
||||
## GitHub infos
|
||||
* Please submit translations as a GitHub pull-request. This way, you can easily work with others and review each other. To submit a pull-request, you need a Github account. Then, fork the entire project (using the button in the upper-right corner).
|
||||
* Then, create a new branch for your translation. Do this using the Github UI or via the terminal inside the project repository: `git checkout -b translation_es` for example. Then, create the appropriate language file and put it in the translations folder. Then, add it to the branch with by navigating to the translations folder `git add es.toml` and `git commit -m 'add spanish'`. Finally, push the branch to your fork `git push --set-upstream origin translation_es`. When done, open a pull-request in the *original github repo* and select your forked branch.
|
||||
* Good luck :)
|
||||
@@ -0,0 +1,343 @@
|
||||
# COMMANDS
|
||||
|
||||
helpCommandStr = """hilfe"""
|
||||
basicsCommandStr = """grundlagen"""
|
||||
tipCommandStr = """tip"""
|
||||
balanceCommandStr = """guthaben"""
|
||||
sendCommandStr = """sende"""
|
||||
invoiceCommandStr = """invoice"""
|
||||
payCommandStr = """bezahle"""
|
||||
donateCommandStr = """spende"""
|
||||
advancedCommandStr = """fortgeschritten"""
|
||||
transactionsCommandStr = """transaktionen"""
|
||||
logCommandStr = """log"""
|
||||
listCommandStr = """liste"""
|
||||
|
||||
linkCommandStr = """verbinde"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """zapfhahn"""
|
||||
|
||||
tipjarCommandStr = """spendendose"""
|
||||
receiveCommandStr = """empfange"""
|
||||
hideCommandStr = """verstecke"""
|
||||
volcanoCommandStr = """vulkan"""
|
||||
showCommandStr = """zeige"""
|
||||
optionsCommandStr = """optionen"""
|
||||
settingsCommandStr = """einstellungen"""
|
||||
saveCommandStr = """save"""
|
||||
deleteCommandStr = """lösche"""
|
||||
infoCommandStr = """info"""
|
||||
|
||||
# NOTIFICATIONS
|
||||
|
||||
cantDoThatMessage = """Du kannst das nicht tun."""
|
||||
cantClickMessage = """Du kannst diesen Knopf nicht drücken."""
|
||||
balanceTooLowMessage = """Dein Guthaben ist zu niedrig."""
|
||||
|
||||
# BUTTONS
|
||||
|
||||
sendButtonMessage = """✅ Senden"""
|
||||
payButtonMessage = """✅ Bezahlen"""
|
||||
payReceiveButtonMessage = """💸 Bezahlen"""
|
||||
receiveButtonMessage = """✅ Empfangen"""
|
||||
withdrawButtonMessage = """✅ Abheben"""
|
||||
cancelButtonMessage = """🚫 Abbrechen"""
|
||||
collectButtonMessage = """✅ Einsammeln"""
|
||||
nextButtonMessage = """Vor"""
|
||||
backButtonMessage = """Zurück"""
|
||||
acceptButtonMessage = """Akzeptieren"""
|
||||
denyButtonMessage = """Verweigern"""
|
||||
tipButtonMessage = """Tip"""
|
||||
revealButtonMessage = """Aufdecken"""
|
||||
showButtonMessage = """Zeigen"""
|
||||
hideButtonMessage = """Verstecken"""
|
||||
joinButtonMessage = """Mitmachen"""
|
||||
optionsButtonMessage = """Optionen"""
|
||||
settingsButtonMessage = """Einstellungen"""
|
||||
saveButtonMessage = """Speichern"""
|
||||
deleteButtonMessage = """Löschen"""
|
||||
infoButtonMessage = """Info"""
|
||||
|
||||
# HELP
|
||||
|
||||
helpMessage = """⚡️ *Wallet*
|
||||
_Dieser Bot ist ein Bitcoin Lightning Wallet der Tips (kleine Beträge) auf Telegram senden kann. Um ein Tip zu senden, füge den Bot in einen Gruppenchat hinzu. Die grundlegende Einheit von Tips sind Satoshis (sat). 100,000,000 sat = 1 Bitcoin. Gebe 📚 /basics ein für mehr Informationen._
|
||||
|
||||
❤️ *Spenden*
|
||||
_Dieser Bot erhebt keine Gebühren, kostet aber Satoshis um betrieben zu werden. Wenn du den Bot magst, kannst das Projekt mit eine Spende unterstützen. Um zu spenden, gebe ein: _ `/donate 1000`
|
||||
|
||||
%s
|
||||
|
||||
⚙️ *Befehle*
|
||||
*/tip* 🏅 Antworte auf eine Nachricht um einen Tip zu senden: `/tip <betrag> [<memo>]`
|
||||
*/balance* 👑 Frage dein Guthaben ab: `/balance`
|
||||
*/send* 💸 Sende an einen Benutzer: `/send <betrag> @user oder user@ln.tips [<memo>]`
|
||||
*/invoice* ⚡️ Empfange mit Lightning: `/invoice <betrag> [<memo>]`
|
||||
*/pay* ⚡️ Bezahle mit Lightning: `/pay <invoice>`
|
||||
*/donate* ❤️ Spende an das Projekt: `/donate 1000`
|
||||
*/advanced* 🤖 Fortgeschrittene Funktionen.
|
||||
*/help* 📖 Rufe die Hilfe auf."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Info*"""
|
||||
infoYourLightningAddress = """Deine Lightning Adresse ist `%s`"""
|
||||
|
||||
basicsMessage = """🧡 *Bitcoin*
|
||||
_Bitcoin ist die Währung des Internets. Bitcoin ist offen für jeden, ist dezentral, und es gibt niemanden, der Bitcoin kontrolliert. Bitcoin ist hartes Geld, welches schneller, sicherer, und fairer ist, als das klassische Finanzsystem._
|
||||
|
||||
🧮 *Ökonomie*
|
||||
_Die kleinste Einheit von Bitcoin sind Satoshis (sat) und 100,000,000 sat = 1 Bitcoin. Es wird niemals mehr als 21 Millionen Bitcoin geben. Der Fiatgeld-Wert von Bitcoin kann sich täglich ändern. Wenn du jedoch auf einem Bitcoin-Standard lebst, wird 1 sat für immer 1 sat Wert sein._
|
||||
|
||||
⚡️ *Das Lightning Netzwerk*
|
||||
_Das Lightning Netzwerk ist ein Bezahlprotokoll, das schnelle und günstige Bitcoin Zahlungen erlaubt, die fast keine Energie kosten. Dadurch skaliert Bitcoin auf Milliarden von Menschen weltweit._
|
||||
|
||||
📲 *Lightning Wallets*
|
||||
_Dein Geld auf diesem Bot kannst du an jedes andere Lightning Wallet der Welt versenden. Empfohlene Lightning Wallets für dein Handy sind _ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (eigene Verwahrung), oder_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(einfach)_.
|
||||
|
||||
📄 *Open Source*
|
||||
_Dieser Bot ist kostenlose_ [Open Source](https://github.com/LightningTipBot/LightningTipBot) _Software. Du kannst ihn auf deinem eigenen Rechner laufen lassen und für deine eigene Community betreiben._
|
||||
|
||||
✈️ *Telegram*
|
||||
_Füge den Bot in deine Telegram Gruppenchats hinzu, um Nachrichten ein /tip zu senden. Wenn der Bot Admin der Gruppe ist, wird er auch den Chat aufräumen, indem er manche Befehle nach Ausführung löscht._
|
||||
|
||||
🏛 *Bedingungen*
|
||||
_Wir sind keine Verwahrer deines Geldes. Wir werden in deinem besten Interesse handeln, aber sind uns auch dessen bewusst, dass die Situation ohne KYC etwas kompliziert ist. Solange wir keine andere Lösung gefunden haben, werden wir alle Beträge auf diesem Bot als Spenden betrachten. Gebe uns nicht dein ganzes Geld. Sei dir dessen bewusst, dass dieser Bot immer noch in der Betaphase ist. Benutzung auf eigene Gefahr._
|
||||
|
||||
❤️ *Spenden*
|
||||
_Dieser Bot erhebt keine Gebühren, kostet aber Satoshis um betrieben zu werden. Wenn du den Bot magst, kannst das Projekt mit eine Spende unterstützen. Um zu spenden, gebe ein: _ `/donate 1000`"""
|
||||
|
||||
helpNoUsernameMessage = """👋 Wähle einen Benutzernamen in den Telegram Einstellungen."""
|
||||
|
||||
advancedMessage = """%s
|
||||
|
||||
👉 *Inline Befehle*
|
||||
*send* 💸 Sende sats an einen Chat: `%s send <betrag> [<user>] [<memo>]`
|
||||
*receive* 🏅 Bitte um Zahlung: `... receive <betrag> [<user>] [<memo>]`
|
||||
*faucet* 🚰 Erzeuge einen Zapfhahn: `... faucet <gesamt> <pro_user> [<memo>]`
|
||||
*tipjar* 🍯 Erzeuge eine Spendendose: `... tipjar <gesamt> <pro_user> [<memo>]`
|
||||
|
||||
📖 Du kannst Inline Befehle in jedem Chat verwenden, sogar in privaten Nachrichten. Warte eine Sekunde, nachdem du den Befehl eingegeben hast und *klicke* auf das Ergebnis, statt Enter einzugeben.
|
||||
|
||||
⚙️ *Fortgeschrittene Befehle*
|
||||
*/link* 🔗 Verbinde dein Wallet mit [BlueWallet](https://bluewallet.io/) oder [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl empfangen oder senden: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Erzeuge einen Zapfhahn: `/faucet <gesamt> <pro_user>`
|
||||
*/tipjar* 🍯 Erzeuge eine Spendendose: `/tipjar <gesamt> <pro_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """⌨️ Gebe einen Betrag zwischen %d und %d sat ein."""
|
||||
enterAmountMessage = """⌨️ Gebe einen Betrag ein."""
|
||||
errorReasonMessage = """🚫 Fehler: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Richte dein Wallet ein..."""
|
||||
startWalletCreatedMessage = """🧮 Wallet erzeugt."""
|
||||
startWalletReadyMessage = """✅ *Dein Wallet ist bereit.*"""
|
||||
startWalletErrorMessage = """🚫 Fehler beim einrichten deines Wallets. Bitte versuche es später noch einmal."""
|
||||
startNoUsernameMessage = """☝️ Es sieht so aus, als hättest du noch keinen Telegram @usernamen. Das ist ok, du brauchst keinen, um diesen Bot zu verwenden. Um jedoch alle Funktionen verwenden zu können, solltest du dir einen Usernamen in den Telegram Einstellungen setzen. Gebe danach ein mal /balance ein, damit der Bot seine Informationen über dich aktualisieren kann."""
|
||||
|
||||
# BALANCE
|
||||
|
||||
balanceMessage = """👑 *Dein Guthaben:* %d sat"""
|
||||
balanceErrorMessage = """🚫 Konnte dein Guthaben nicht abfragen. Bitte versuche es später noch einmal."""
|
||||
|
||||
# TIP
|
||||
|
||||
tipDidYouReplyMessage = """Hast du auf eine Nachricht geantwortet um ihr ein Tip zu senden? Um zu antworten, rechts-klicke die Nachricht auf deinem Computer oder wische die Nachricht auf deinem Handy. Wenn du direkt Zahlungen an einen anderen Nutzer senden möchtest, benutze den /send Befehl."""
|
||||
tipInviteGroupMessage = """ℹ️ Übrigens, du kannst diesen Bot in jeden Gruppenchat einladen und dort Tips verteilen."""
|
||||
tipEnterAmountMessage = """Hast du einen Betrag eingegeben?"""
|
||||
tipValidAmountMessage = """Hast du einen gültigen Betrag eingegeben?"""
|
||||
tipYourselfMessage = """📖 Du kannst dir nicht selbst Tips senden."""
|
||||
tipSentMessage = """💸 %d sat an %s gesendet."""
|
||||
tipReceivedMessage = """🏅 %s hat dir ein Tip von %d sat gesendet."""
|
||||
tipErrorMessage = """🚫 Tip fehlgeschlagen."""
|
||||
tipUndefinedErrorMsg = """bitte versuche es später noch einmal."""
|
||||
tipHelpText = """📖 Ups, das hat nicht geklappt. %s
|
||||
|
||||
*Befehl:* `/tip <betrag> [<memo>]`
|
||||
*Beispiel:* `/tip 1000 Geiles Meme!`"""
|
||||
|
||||
# SEND
|
||||
|
||||
sendValidAmountMessage = """Hast du einen gültigen Betrag eingegeben?"""
|
||||
sendUserHasNoWalletMessage = """🚫 Der Benutzer %s hat noch keinen Wallet erstellt."""
|
||||
sendSentMessage = """💸 %d sat gesendet an %s."""
|
||||
sendPublicSentMessage = """💸 %d sat gesendet von %s an %s."""
|
||||
sendReceivedMessage = """🏅 %s hat dir %d sat gesendet."""
|
||||
sendErrorMessage = """🚫 Senden fehlgeschlagen."""
|
||||
confirmSendMessage = """Möchtest eine Zahlung an %s senden?\n\n💸 Betrag: %d sat"""
|
||||
confirmSendAppendMemo = """\n✉️ %s"""
|
||||
sendCancelledMessage = """🚫 Senden abgebrochen."""
|
||||
errorTryLaterMessage = """🚫 Fehler. Bitte versuche es später noch einmal."""
|
||||
sendSyntaxErrorMessage = """Hast du einen gültigen Betrag und Empfänger eingegeben? Du kannst den /send Befehl verwenden, um entweder an Telegram Nutzer zu senden, wie z.B. %s oder an eine Lightning Adresse, wie LightningTipBot@ln.tips."""
|
||||
sendHelpText = """📖 Ups, das hat nicht geklappt. %s
|
||||
|
||||
*Befehl:* `/send <betrag> <user> [<memo>]`
|
||||
*Beispiel:* `/send 1000 @LightningTipBot Ich liebe diesen Bot ❤️`
|
||||
*Beispiel:* `/send 1234 LightningTipBot@ln.tips`"""
|
||||
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Du hast %d sat erhalten."""
|
||||
invoiceEnterAmountMessage = """Hast du einen Betrag eingegeben?"""
|
||||
invoiceValidAmountMessage = """Hast du einen gültigen Betrag eingegeben?"""
|
||||
invoiceHelpText = """📖 Ups, das hat nicht geklappt. %s
|
||||
|
||||
*Befehl:* `/invoice <betrag> [<memo>]`
|
||||
*Beispiel:* `/invoice 1000 Thank you!`"""
|
||||
|
||||
# PAY
|
||||
|
||||
paymentCancelledMessage = """🚫 Zahlung abgebrochen."""
|
||||
invoicePaidMessage = """⚡️ Zahlung gesendet."""
|
||||
invoicePublicPaidMessage = """⚡️ Zahlung gesendet von %s."""
|
||||
invalidInvoiceHelpMessage = """Hast du eine gültige Lightning Invoice eingegeben? Versuche den /send Befehl, falls du an einen Telegram Nutzer oder eine Lightning Adresse senden willst."""
|
||||
invoiceNoAmountMessage = """🚫 Kann keine Invoices ohne Betrag bezahlen."""
|
||||
insufficientFundsMessage = """🚫 Guthaben zu niedrig. Du hast %d sat aber brauchst mindestens %d sat."""
|
||||
feeReserveMessage = """⚠️ Dein gesamtes Guthaben zu senden könnte wegen den Netzwerkgebühren fehlschlagen. Falls das passiert, versuche es mit einem etwas geringeren Betrag."""
|
||||
invoicePaymentFailedMessage = """🚫 Zahlung fehlgeschlagen: %s"""
|
||||
invoiceUndefinedErrorMessage = """Konnte Invoice nicht bezahlen."""
|
||||
confirmPayInvoiceMessage = """Möchtest du diese Zahlung senden?\n\n💸 Betrag: %d sat"""
|
||||
confirmPayAppendMemo = """\n✉️ %s"""
|
||||
payHelpText = """📖 Ups, das hat nicht geklappt. %s
|
||||
|
||||
*Befehl:* `/pay <invoice>`
|
||||
*Beispiel:* `/pay lnbc20n1psscehd...`"""
|
||||
|
||||
# DONATE
|
||||
|
||||
donationSuccess = """🙏 Danke für deine Spende."""
|
||||
donationErrorMessage = """🚫 Oh nein. Spende fehlgeschlagen."""
|
||||
donationProgressMessage = """🧮 Bereite deine Spende vor..."""
|
||||
donationFailedMessage = """🚫 Spende fehlgeschlagen: %s"""
|
||||
donateEnterAmountMessage = """Hast du deinen Betrag eingegeben?"""
|
||||
donateValidAmountMessage = """Hast du einen gültigen Betrag eingegeben?"""
|
||||
donateHelpText = """📖 Ups, das hat nicht geklappt. %s
|
||||
|
||||
*Befehl:* `/donate <betrag>`
|
||||
*Beispiel:* `/donate 1000`"""
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 Keine Lightning Invoice oder LNURL erkannt. Versuche den QR Code zu zentrieren, beschneide ihn oder zoome mehr heran."""
|
||||
photoQrRecognizedMessage = """✅ QR Code:
|
||||
`%s`"""
|
||||
|
||||
# LNURL
|
||||
|
||||
lnurlReceiveInfoText = """👇 Du kannst diese statische LNURL benutzen um bezahlt zu werden."""
|
||||
lnurlResolvingUrlMessage = """🧮 Löse Adresse auf..."""
|
||||
lnurlGettingUserMessage = """🧮 Bereite Zahlung vor..."""
|
||||
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."""
|
||||
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*
|
||||
|
||||
⚠️ Teile diese URL und den QR code mit niemandem! Jeder, der darauf Zugriff hat, hat auch Zugriff auf dein Konto.
|
||||
|
||||
- *BlueWallet:* Drücke *New wallet*, *Import wallet*, *Scan or import a file*, und scanne den QR Code.
|
||||
- *Zeus:* Kopiere die URL unten, drücke *Add a new node*, *Import* (die URL), *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Konnte dein Wallet nicht verbinden. Bitte versuche es später noch einmal."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
inlineQueryFaucetTitle = """🚰 Erzeuge einen Zapfhahn."""
|
||||
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.
|
||||
|
||||
🚰 Verbleibend: %d/%d sat (%d/%d gezapft)
|
||||
%s"""
|
||||
inlineFaucetEndedMessage = """🚰 Zapfhahn leer 🍺\n\n🏅 %d sat an %d User ausgeschüttet."""
|
||||
inlineFaucetAppendMemo = """\n✉️ %s"""
|
||||
inlineFaucetCreateWalletMessage = """Chatte mit %s 👈 um dein Wallet zu verwalten."""
|
||||
inlineFaucetCancelledMessage = """🚫 Zapfhahn abgebrochen."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 Die Pro-User Menge muss ein natürlicher Teiler der Gesamtmenge sein."""
|
||||
inlineFaucetInvalidAmountMessage = """🚫 Ungültige Menge."""
|
||||
inlineFaucetSentMessage = """🚰 %d sat an %s gesendet."""
|
||||
inlineFaucetReceivedMessage = """🚰 %s hat dir %d sat gesendet."""
|
||||
inlineFaucetHelpFaucetInGroup = """Erzeuge einen Zapfhahn in einer Gruppe, wo der Bot eingeladen ist oder benutze einen 👉 Inline Befehl (/advanced für mehr)."""
|
||||
inlineFaucetHelpText = """📖 Ups, das hat nicht geklappt. %s
|
||||
|
||||
*Befehl:* `/faucet <gesamt> <pro_user>`
|
||||
*Beispiel:* `/faucet 210 21`"""
|
||||
|
||||
# INLINE SEND
|
||||
|
||||
inlineQuerySendTitle = """💸 Sende Zahlungen in einem Chat."""
|
||||
inlineQuerySendDescription = """Befehl: @%s send <betrag> [<user>] [<memo>]"""
|
||||
inlineResultSendTitle = """💸 Sende %d sat."""
|
||||
inlineResultSendDescription = """👉 Klicke hier um %d sat in diesen Chat zu senden."""
|
||||
|
||||
inlineSendMessage = """Klicke ✅ um eine Zahlung von %s zu erhalten.\n\n💸 Betrag: %d sat"""
|
||||
inlineSendAppendMemo = """\n✉️ %s"""
|
||||
inlineSendUpdateMessageAccept = """💸 %d sat gesendet von %s an %s."""
|
||||
inlineSendCreateWalletMessage = """Chatte mit %s 👈 um dein Wallet zu verwalten."""
|
||||
sendYourselfMessage = """📖 Du kannst dich nicht selbst bezahlen."""
|
||||
inlineSendFailedMessage = """🚫 Senden fehlgeschlagen."""
|
||||
inlineSendInvalidAmountMessage = """🚫 Betrag muss größer als 0 sein."""
|
||||
inlineSendBalanceLowMessage = """🚫 Dein Guthaben reicht nicht aus."""
|
||||
|
||||
# INLINE RECEIVE
|
||||
|
||||
inlineQueryReceiveTitle = """🏅 Empfange eine Zahlung in einem Chat."""
|
||||
inlineQueryReceiveDescription = """Befehl: @%s receive <betrag> [<pro_user>] [<memo>]"""
|
||||
inlineResultReceiveTitle = """🏅 Empfange %d sat."""
|
||||
inlineResultReceiveDescription = """👉 Klicke hier um eine Zahlung von %d sat zu empfangen."""
|
||||
|
||||
inlineReceiveMessage = """Drücke 💸 um an %s zu zahlen.\n\n💸 Betrag: %d sat"""
|
||||
inlineReceiveAppendMemo = """\n✉️ %s"""
|
||||
inlineReceiveUpdateMessageAccept = """💸 %d sat gesendet von %s an %s."""
|
||||
inlineReceiveCreateWalletMessage = """Chatte mit %s 👈 um dein Wallet zu verwalten."""
|
||||
inlineReceiveYourselfMessage = """📖 Du kannst dich nicht selbst bezahlen."""
|
||||
inlineReceiveFailedMessage = """🚫 Empfangen fehlgeschlagen."""
|
||||
inlineReceiveCancelledMessage = """🚫 Empfangen abgebrochen."""
|
||||
|
||||
# TIPJAR
|
||||
|
||||
inlineQueryTipjarTitle = """🍯 Erzeuge eine Spendendose."""
|
||||
inlineQueryTipjarDescription = """Befehl: @%s tipjar <betrag> <pro_user>"""
|
||||
inlineResultTipjarTitle = """🍯 Erzeuge eine Spendendose für %d sat."""
|
||||
inlineResultTipjarDescription = """👉 Klicke hier um eine Spendendose zu erzeugen."""
|
||||
|
||||
inlineTipjarMessage = """Drücke 💸 up *%d sat* in die Spendendose von %s zu *zahlen*.
|
||||
|
||||
🙏 Gespendet: *%d*/%d sat (von %d Benutzern)
|
||||
%s"""
|
||||
inlineTipjarEndedMessage = """🍯 %s's Spendendose is voll ⭐️\n\n🏅 %d sat gespendet von %d Nutzern."""
|
||||
inlineTipjarAppendMemo = """\n✉️ %s"""
|
||||
inlineTipjarCancelledMessage = """🚫 Spendendose abgebrochen."""
|
||||
inlineTipjarInvalidPeruserAmountMessage = """🚫 Die Pro-User Menge muss ein natürlicher Teiler der Gesamtmenge sein."""
|
||||
inlineTipjarInvalidAmountMessage = """🚫 Ungültige Menge."""
|
||||
inlineTipjarSentMessage = """🍯 %d sat an %s gesendet."""
|
||||
inlineTipjarReceivedMessage = """🍯 %s hat dir %d sat gesendet."""
|
||||
inlineTipjarHelpTipjarInGroup = """Erzeuge eine Spendendose in einer Gruppe, wo der Bot eingeladen ist oder benutze einen 👉 Inline Befehl (/advanced für mehr)."""
|
||||
inlineTipjarHelpText = """📖 Ups, das hat nicht geklappt. %s
|
||||
|
||||
*Befehl:* `/tipjar <betrag> <pro_user>`
|
||||
*Beispiel:* `/tipjar 210 21`"""
|
||||
@@ -0,0 +1,349 @@
|
||||
# COMMANDS
|
||||
|
||||
helpCommandStr = """help"""
|
||||
basicsCommandStr = """basics"""
|
||||
tipCommandStr = """tip"""
|
||||
balanceCommandStr = """balance"""
|
||||
sendCommandStr = """send"""
|
||||
invoiceCommandStr = """invoice"""
|
||||
payCommandStr = """pay"""
|
||||
donateCommandStr = """donate"""
|
||||
advancedCommandStr = """advanced"""
|
||||
transactionsCommandStr = """transactions"""
|
||||
logCommandStr = """log"""
|
||||
listCommandStr = """list"""
|
||||
|
||||
linkCommandStr = """link"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """faucet"""
|
||||
|
||||
tipjarCommandStr = """tipjar"""
|
||||
receiveCommandStr = """receive"""
|
||||
hideCommandStr = """hide"""
|
||||
volcanoCommandStr = """volcano"""
|
||||
showCommandStr = """show"""
|
||||
optionsCommandStr = """options"""
|
||||
settingsCommandStr = """settings"""
|
||||
saveCommandStr = """save"""
|
||||
deleteCommandStr = """delete"""
|
||||
infoCommandStr = """info"""
|
||||
|
||||
# NOTIFICATIONS
|
||||
|
||||
cantDoThatMessage = """You can't do that."""
|
||||
cantClickMessage = """You can't click this button."""
|
||||
balanceTooLowMessage = """Your balance is too low."""
|
||||
|
||||
# BUTTONS
|
||||
|
||||
sendButtonMessage = """✅ Send"""
|
||||
payButtonMessage = """✅ Pay"""
|
||||
payReceiveButtonMessage = """💸 Pay"""
|
||||
receiveButtonMessage = """✅ Receive"""
|
||||
withdrawButtonMessage = """✅ Withdraw"""
|
||||
cancelButtonMessage = """🚫 Cancel"""
|
||||
collectButtonMessage = """✅ Collect"""
|
||||
nextButtonMessage = """Next"""
|
||||
backButtonMessage = """Back"""
|
||||
acceptButtonMessage = """Accept"""
|
||||
denyButtonMessage = """Deny"""
|
||||
tipButtonMessage = """Tip"""
|
||||
revealButtonMessage = """Reveal"""
|
||||
showButtonMessage = """Show"""
|
||||
hideButtonMessage = """Hide"""
|
||||
joinButtonMessage = """Join"""
|
||||
optionsButtonMessage = """Options"""
|
||||
settingsButtonMessage = """Settings"""
|
||||
saveButtonMessage = """Save"""
|
||||
deleteButtonMessage = """Delete"""
|
||||
infoButtonMessage = """Info"""
|
||||
|
||||
cancelButtonEmoji = """🚫"""
|
||||
payButtonEmoji = """💸"""
|
||||
|
||||
# HELP
|
||||
|
||||
helpMessage = """⚡️ *Wallet*
|
||||
_This bot is a Bitcoin Lightning wallet that can sends tips on Telegram. To tip, add the bot to a group chat. The basic unit of tips are Satoshis (sat). 100,000,000 sat = 1 Bitcoin. Type 📚 /basics for more._
|
||||
|
||||
❤️ *Donate*
|
||||
_This bot charges no fees but costs Satoshis to operate. If you like the bot, please consider supporting this project with a donation. To donate, use_ `/donate 1000`
|
||||
|
||||
%s
|
||||
|
||||
⚙️ *Commands*
|
||||
*/tip* 🏅 Reply to a message to tip: `/tip <amount> [<memo>]`
|
||||
*/balance* 👑 Check your balance: `/balance`
|
||||
*/send* 💸 Send funds to a user: `/send <amount> @user or user@ln.tips [<memo>]`
|
||||
*/invoice* ⚡️ Receive with Lightning: `/invoice <amount> [<memo>]`
|
||||
*/pay* ⚡️ Pay with Lightning: `/pay <invoice>`
|
||||
*/donate* ❤️ Donate to the project: `/donate 1000`
|
||||
*/advanced* 🤖 Advanced features.
|
||||
*/help* 📖 Read this help."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Info*"""
|
||||
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._
|
||||
|
||||
🧮 *Economnics*
|
||||
_The smallest unit of Bitcoin are Satoshis (sat) and 100,000,000 sat = 1 Bitcoin. There will only ever be 21 Million Bitcoin. The fiat currency value of Bitcoin can change daily. However, if you live on a Bitcoin standard 1 sat will always equal 1 sat._
|
||||
|
||||
⚡️ *The Lightning Network*
|
||||
_The Lightning Network is a payment protocol that enables fast and cheap Bitcoin payments that require almost no energy. It is what scales Bitcoin to the billions of people around the world._
|
||||
|
||||
📲 *Lightning Wallets*
|
||||
_Your funds on this bot can be sent to any other Lightning wallet and vice versa. Recommended Lightning wallets for your phone are_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (non-custodial), or_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(easy)_.
|
||||
|
||||
📄 *Open Source*
|
||||
_This bot is free and_ [open source](https://github.com/LightningTipBot/LightningTipBot) _software. You can run it on your own computer and use it in your own community._
|
||||
|
||||
✈️ *Telegram*
|
||||
_Add this bot to your Telegram group chat to /tip posts. If you make the bot admin of the group it will also clean up commands to keep the chat tidy._
|
||||
|
||||
🏛 *Terms*
|
||||
_We are not custodian of your funds. We will act in your best interest but we're also aware that the situation without KYC is tricky until we figure something out. Any amount you load onto your wallet will be considered a donation. Do not give us all your money. Be aware that this bot is in beta development. Use at your own risk._
|
||||
|
||||
❤️ *Donate*
|
||||
_This bot charges no fees but costs satoshis to operate. If you like the bot, please consider supporting this project with a donation. To donate, use_ `/donate 1000`"""
|
||||
|
||||
helpNoUsernameMessage = """👋 Please, set a Telegram username."""
|
||||
|
||||
advancedMessage = """%s
|
||||
|
||||
👉 *Inline commands*
|
||||
*send* 💸 Send sats to chat: `%s send <amount> [<user>] [<memo>]`
|
||||
*receive* 🏅 Request a payment: `... receive <amount> [<user>] [<memo>]`
|
||||
*faucet* 🚰 Create a faucet: `... faucet <capacity> <per_user> [<memo>]`
|
||||
*tipjar* 🍯 Create a tipjar: `... tipjar <capacity> <per_user> [<memo>]`
|
||||
|
||||
📖 You can use inline commands in every chat, even in private conversations. Wait a second after entering an inline command and *click* the result, don't press enter.
|
||||
|
||||
⚙️ *Advanced commands*
|
||||
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl receive or pay: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Create a faucet: `/faucet <capacity> <per_user>`
|
||||
*/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..."""
|
||||
startWalletCreatedMessage = """🧮 Wallet created."""
|
||||
startWalletReadyMessage = """✅ *Your wallet is ready.*"""
|
||||
startWalletErrorMessage = """🚫 Error initializing your wallet. Try again later."""
|
||||
startNoUsernameMessage = """☝️ It looks like you don't have a Telegram @username yet. That's ok, you don't need one to use this bot. However, to make better use of your wallet, set up a username in the Telegram settings. Then, enter /balance so the bot can update its record of you."""
|
||||
|
||||
# BALANCE
|
||||
|
||||
balanceMessage = """👑 *Your balance:* %d sat"""
|
||||
balanceErrorMessage = """🚫 Could not fetch your balance. Please try again later."""
|
||||
|
||||
# TIP
|
||||
|
||||
tipDidYouReplyMessage = """Did you reply to a message to tip? To reply to any message, right-click -> Reply on your computer or swipe the message on your phone. If you want to send directly to another user, use the /send command."""
|
||||
tipInviteGroupMessage = """ℹ️ By the way, you can invite this bot to any group to start tipping there."""
|
||||
tipEnterAmountMessage = """Did you enter an amount?"""
|
||||
tipValidAmountMessage = """Did you enter a valid amount?"""
|
||||
tipYourselfMessage = """📖 You can't tip yourself."""
|
||||
tipSentMessage = """💸 %d sat sent to %s."""
|
||||
tipReceivedMessage = """🏅 %s has tipped you %d sat."""
|
||||
tipErrorMessage = """🚫 Tip failed."""
|
||||
tipUndefinedErrorMsg = """please try again later."""
|
||||
tipHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
*Usage:* `/tip <amount> [<memo>]`
|
||||
*Example:* `/tip 1000 Dank meme!`"""
|
||||
|
||||
# SEND
|
||||
|
||||
sendValidAmountMessage = """Did you enter a valid amount?"""
|
||||
sendUserHasNoWalletMessage = """🚫 User %s hasn't created a wallet yet."""
|
||||
sendSentMessage = """💸 %d sat sent to %s."""
|
||||
sendPublicSentMessage = """💸 %d sat sent from %s to %s."""
|
||||
sendReceivedMessage = """🏅 %s sent you %d sat."""
|
||||
sendErrorMessage = """🚫 Send failed."""
|
||||
confirmSendMessage = """Do you want to pay to %s?\n\n💸 Amount: %d sat"""
|
||||
confirmSendAppendMemo = """\n✉️ %s"""
|
||||
sendCancelledMessage = """🚫 Send cancelled."""
|
||||
errorTryLaterMessage = """🚫 Error. Please try again later."""
|
||||
sendSyntaxErrorMessage = """Did you enter an amount and a recipient? You can use the /send command to either send to Telegram users like %s or to a Lightning address like LightningTipBot@ln.tips."""
|
||||
sendHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
*Usage:* `/send <amount> <user> [<memo>]`
|
||||
*Example:* `/send 1000 @LightningTipBot I just like the bot ❤️`
|
||||
*Example:* `/send 1234 LightningTipBot@ln.tips`"""
|
||||
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ You received %d sat."""
|
||||
invoiceEnterAmountMessage = """Did you enter an amount?"""
|
||||
invoiceValidAmountMessage = """Did you enter a valid amount?"""
|
||||
invoiceHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
*Usage:* `/invoice <amount> [<memo>]`
|
||||
*Example:* `/invoice 1000 Thank you!`"""
|
||||
|
||||
# PAY
|
||||
|
||||
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."""
|
||||
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."""
|
||||
invoicePaymentFailedMessage = """🚫 Payment failed: %s"""
|
||||
invoiceUndefinedErrorMessage = """Could not pay invoice."""
|
||||
confirmPayInvoiceMessage = """Do you want to send this payment?\n\n💸 Amount: %d sat"""
|
||||
confirmPayAppendMemo = """\n✉️ %s"""
|
||||
payHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
*Usage:* `/pay <invoice>`
|
||||
*Example:* `/pay lnbc20n1psscehd...`"""
|
||||
|
||||
# DONATE
|
||||
|
||||
donationSuccess = """🙏 Thank you for your donation."""
|
||||
donationErrorMessage = """🚫 Oh no. Donation failed."""
|
||||
donationProgressMessage = """🧮 Preparing your donation..."""
|
||||
donationFailedMessage = """🚫 Donation failed: %s"""
|
||||
donateEnterAmountMessage = """Did you enter an amount?"""
|
||||
donateValidAmountMessage = """Did you enter a valid amount?"""
|
||||
donateHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
*Usage:* `/donate <amount>`
|
||||
*Example:* `/donate 1000`"""
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 Could not regocognize a Lightning invoice or an LNURL. Try to center the QR code, crop the photo, or zoom in."""
|
||||
photoQrRecognizedMessage = """✅ QR code:
|
||||
`%s`"""
|
||||
|
||||
# LNURL
|
||||
|
||||
lnurlReceiveInfoText = """👇 You can use this static LNURL to receive payments."""
|
||||
lnurlResolvingUrlMessage = """🧮 Resolving address..."""
|
||||
lnurlGettingUserMessage = """🧮 Preparing payment..."""
|
||||
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."""
|
||||
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*
|
||||
|
||||
⚠️ Never share the URL or the QR code with anyone or they will be able to access your funds.
|
||||
|
||||
- *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."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
inlineQueryFaucetTitle = """🚰 Create a faucet."""
|
||||
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.
|
||||
|
||||
🚰 Remaining: %d/%d sat (given to %d/%d users)
|
||||
%s"""
|
||||
inlineFaucetEndedMessage = """🚰 Faucet empty 🍺\n\n🏅 %d sat given to %d users."""
|
||||
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)."""
|
||||
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>`
|
||||
*Example:* `/faucet 210 21`"""
|
||||
|
||||
# INLINE SEND
|
||||
|
||||
inlineQuerySendTitle = """💸 Send payment to a chat."""
|
||||
inlineQuerySendDescription = """Usage: @%s send <amount> [<user>] [<memo>]"""
|
||||
inlineResultSendTitle = """💸 Send %d sat."""
|
||||
inlineResultSendDescription = """👉 Click to send %d sat to this chat."""
|
||||
|
||||
inlineSendMessage = """Press ✅ to receive payment from %s.\n\n💸 Amount: %d sat"""
|
||||
inlineSendAppendMemo = """\n✉️ %s"""
|
||||
inlineSendUpdateMessageAccept = """💸 %d sat sent from %s to %s."""
|
||||
inlineSendCreateWalletMessage = """Chat with %s 👈 to manage your wallet."""
|
||||
sendYourselfMessage = """📖 You can't pay to yourself."""
|
||||
inlineSendFailedMessage = """🚫 Send failed."""
|
||||
inlineSendInvalidAmountMessage = """🚫 Amount must be larger than 0."""
|
||||
inlineSendBalanceLowMessage = """🚫 Your balance is too low."""
|
||||
|
||||
# INLINE RECEIVE
|
||||
|
||||
inlineQueryReceiveTitle = """🏅 Request a payment in a chat."""
|
||||
inlineQueryReceiveDescription = """Usage: @%s receive <amount> [<user>] [<memo>]"""
|
||||
inlineResultReceiveTitle = """🏅 Receive %d sat."""
|
||||
inlineResultReceiveDescription = """👉 Click to request a payment of %d sat."""
|
||||
|
||||
inlineReceiveMessage = """Press 💸 to pay to %s.\n\n💸 Amount: %d sat"""
|
||||
inlineReceiveAppendMemo = """\n✉️ %s"""
|
||||
inlineReceiveUpdateMessageAccept = """💸 %d sat sent from %s to %s."""
|
||||
inlineReceiveCreateWalletMessage = """Chat with %s 👈 to manage your wallet."""
|
||||
inlineReceiveYourselfMessage = """📖 You can't pay to yourself."""
|
||||
inlineReceiveFailedMessage = """🚫 Receive failed."""
|
||||
inlineReceiveCancelledMessage = """🚫 Receive cancelled."""
|
||||
|
||||
# TIPJAR
|
||||
|
||||
inlineQueryTipjarTitle = """🍯 Create a tipjar."""
|
||||
inlineQueryTipjarDescription = """Usage: @%s tipjar <capacity> <per_user>"""
|
||||
inlineResultTipjarTitle = """🍯 Create a %d sat tipjar."""
|
||||
inlineResultTipjarDescription = """👉 Click here to create a tipjar in this chat."""
|
||||
|
||||
inlineTipjarMessage = """Press 💸 to *pay %d sat* to this tipjar by %s.
|
||||
|
||||
🙏 Given: *%d*/%d sat (by %d users)
|
||||
%s"""
|
||||
inlineTipjarEndedMessage = """🍯 %s's tipjar is full ⭐️\n\n🏅 %d sat given by %d users."""
|
||||
inlineTipjarAppendMemo = """\n✉️ %s"""
|
||||
inlineTipjarCancelledMessage = """🚫 Tipjar cancelled."""
|
||||
inlineTipjarInvalidPeruserAmountMessage = """🚫 Peruser amount not divisor of capacity."""
|
||||
inlineTipjarInvalidAmountMessage = """🚫 Invalid amount."""
|
||||
inlineTipjarSentMessage = """🍯 %d sat sent to %s."""
|
||||
inlineTipjarReceivedMessage = """🍯 %s sent you %d sat."""
|
||||
inlineTipjarHelpTipjarInGroup = """Create a tipjar in a group with the bot inside or use 👉 inline command (/advanced for more)."""
|
||||
inlineTipjarHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
*Usage:* `/tipjar <capacity> <per_user>`
|
||||
*Example:* `/tipjar 210 21`"""
|
||||
@@ -0,0 +1,343 @@
|
||||
# COMMANDS
|
||||
|
||||
helpCommandStr = """ayuda"""
|
||||
basicsCommandStr = """fundamentos"""
|
||||
tipCommandStr = """tip"""
|
||||
balanceCommandStr = """saldo"""
|
||||
sendCommandStr = """enviar"""
|
||||
invoiceCommandStr = """factura"""
|
||||
payCommandStr = """pagar"""
|
||||
donateCommandStr = """donar"""
|
||||
advancedCommandStr = """avanzado"""
|
||||
transactionsCommandStr = """transacciones"""
|
||||
logCommandStr = """log"""
|
||||
listCommandStr = """lista"""
|
||||
|
||||
linkCommandStr = """enlace"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """grifo"""
|
||||
|
||||
tipjarCommandStr = """alcancía"""
|
||||
receiveCommandStr = """recibir"""
|
||||
hideCommandStr = """ocultar"""
|
||||
volcanoCommandStr = """volcán"""
|
||||
showCommandStr = """mostrar"""
|
||||
optionsCommandStr = """opciones"""
|
||||
settingsCommandStr = """ajustes"""
|
||||
saveCommandStr = """guardar"""
|
||||
deleteCommandStr = """borrar"""
|
||||
infoCommandStr = """info"""
|
||||
|
||||
# NOTIFICATIONS
|
||||
|
||||
cantDoThatMessage = """No puedes hacer eso."""
|
||||
cantClickMessage = """No puedes dar click en este botón."""
|
||||
balanceTooLowMessage = """Tu saldo es muy bajo."""
|
||||
|
||||
# BUTTONS
|
||||
|
||||
sendButtonMessage = """✅ Enviar"""
|
||||
payButtonMessage = """✅ Pagar"""
|
||||
payReceiveButtonMessage = """💸 Pagar"""
|
||||
receiveButtonMessage = """✅ Recibir"""
|
||||
cancelButtonMessage = """🚫 Cancelar"""
|
||||
collectButtonMessage = """✅ Cobrar"""
|
||||
nextButtonMessage = """Siguiente"""
|
||||
backButtonMessage = """Volver"""
|
||||
acceptButtonMessage = """Aceptar"""
|
||||
denyButtonMessage = """Negar"""
|
||||
tipButtonMessage = """Tip"""
|
||||
revealButtonMessage = """Revelar"""
|
||||
showButtonMessage = """Mostrar"""
|
||||
hideButtonMessage = """Ocultar"""
|
||||
joinButtonMessage = """Unir"""
|
||||
optionsButtonMessage = """Opciones"""
|
||||
settingsButtonMessage = """Ajustes"""
|
||||
saveButtonMessage = """Guardar"""
|
||||
deleteButtonMessage = """Borrar"""
|
||||
infoButtonMessage = """Info"""
|
||||
|
||||
# HELP
|
||||
|
||||
helpMessage = """⚡️ *Monedero*
|
||||
_Este bot es un monedero Bitcoin Lightning que puede enviar tips (propinas) vía Telegram. Para dar tips, añade el bot a un chat de grupo. La unidad básica de los tips son los Satoshis (sat). 100.000.000 sat = 1 Bitcoin. Escribe 📚 /basics para saber más._
|
||||
|
||||
❤️ *Donar*
|
||||
_Este bot no cobra ninguna comisión, pero su funcionamiento cuesta Satoshis. Si te gusta el bot, por favor considera apoyar este proyecto con una donación. Para donar, usa_ `/donate 1000`.
|
||||
|
||||
%s
|
||||
|
||||
⚙️ *Comandos*
|
||||
*/tip* 🏅 Responder a un mensaje para dar tip: `/tip <monto> [<memo>]`
|
||||
*/balance* 👑 Consulta tu saldo: `/balance`.
|
||||
*/send* 💸 Enviar fondos a un usuario: `/send <monto> @user o user@ln.tips [<memo>]`
|
||||
*/invoice* ⚡️ Recibir con Lightning: `/invoice <monto> [<memo>]`
|
||||
*/pay* ⚡️ Pagar con Lightning: `/pay <invoice>`
|
||||
*/donate* ❤️ Donar al proyecto: `/donate 1000`
|
||||
*/advanced* 🤖 Funciones avanzadas.
|
||||
*/help* 📖 Leer esta ayuda."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Info*"""
|
||||
infoYourLightningAddress = """Su Lightning Address _(Dirección Lightning)_ es `%s`."""
|
||||
|
||||
basicsMessage = """🧡 *Bitcoin*
|
||||
_Bitcoin es la moneda de Internet. Es una moneda sin permisos y descentralizada que no tiene dueños ni autoridad que la controle. Bitcoin es un dinero sólido que es más rápido, más seguro y más inclusivo que el sistema financiero fiduciario._
|
||||
|
||||
🧮 *Economía*
|
||||
_La unidad más pequeña de Bitcoin son los Satoshis (sat) y 100.000.000 sat = 1 Bitcoin. Sólo habrá 21 millones de Bitcoin. El valor de Bitcoin en moneda fiduciaria puede cambiar diariamente. Sin embargo, si vives en el patrón Bitcoin, 1 sat siempre será igual a 1 sat._
|
||||
|
||||
⚡️ *La Red Lightning*
|
||||
_La red Lightning es un protocolo de pago que permite realizar pagos con Bitcoin de forma rápida y barata, con mínimo consumo de energía. Es lo que hace escalar Bitcoin a miles de millones de personas en todo el mundo._
|
||||
|
||||
📲 *Monederos Lightning*
|
||||
_Tus fondos en este bot pueden ser enviados a cualquier otro monedero Lightning y viceversa. Los monederos Lightning recomendados para su teléfono son_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (sin custodia), o_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(fácil)_.
|
||||
|
||||
📄 *Código abierto*
|
||||
_Este bot es gratuito y de_ [Código abierto](https://github.com/LightningTipBot/LightningTipBot)_. Puedes ejecutarlo en tu propio ordenador y utilizarlo en tu propia comunidad._
|
||||
|
||||
✈️ *Telegram*
|
||||
_Añade este bot al chat de tu grupo de Telegram para enviar fondos usando /tip. Si haces al bot administrador del grupo, también limpiará los comandos para mantener el chat ordenado._
|
||||
|
||||
🏛 *Términos*
|
||||
_No somos custodios de tus fondos. Actuaremos en su mejor interés, pero también somos conscientes de que la situación sin KYC es complicada hasta que demos con una solución óptima. Cualquier cantidad que pongas en tu monedero se considerará una donación. No nos des todo tu dinero. Ten en cuenta que este bot está en desarrollo beta. Utilízalo bajo tu propio riesgo._
|
||||
|
||||
❤️ *Donar*
|
||||
_Este bot no cobra ninguna comisión, pero su funcionamiento cuesta satoshis. Si te gusta el bot, por favor considera apoyar este proyecto con una donación. Para donar, use_ `/donate 1000`"""
|
||||
|
||||
helpNoUsernameMessage = """👋 Por favor, pon un nombre de usuario de Telegram."""
|
||||
|
||||
advancedMessage = """%s
|
||||
|
||||
👉 *Comandos Inline*
|
||||
*send* 💸 Enviar sats al chat: `%s send <monto> [<usario>] [<memo>]`
|
||||
*receive* 🏅 Solicita un pago: `... receive <monto> [<usario>] [<memo>]`
|
||||
*faucet* 🚰 Crear un grifo: `... faucet <capacidad> <por_usuario> [<memo>]`
|
||||
*tipjar* 🍯 Crear un tipjar: `... tipjar <capacidad> <por_usuario> [<memo>]`
|
||||
|
||||
📖 Puedes usar comandos _inline_ en todos los chats, incluso en las conversaciones privadas. Espera un segundo después de introducir un comando _inline_ y *haz clic* en el resultado, no pulses enter.
|
||||
|
||||
⚙️ *Comandos avanzados*
|
||||
*/link* 🔗 Enlaza tu monedero a [ BlueWallet ](https://bluewallet.io/) o [ Zeus ](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl recibir o pagar: `/lnurl` o `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Crear un grifo: `/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..."""
|
||||
startWalletCreatedMessage = """🧮 Monedero creado."""
|
||||
startWalletReadyMessage = """✅ *Tu monedero está listo.*"""
|
||||
startWalletErrorMessage = """🚫 Error al iniciar tu monedero. Vuelve a intentarlo más tarde."""
|
||||
startNoUsernameMessage = """☝️ Parece que aún no tienes un @nombredeusuario en Telegram. No pasa nada, no necesitas uno para usar este bot. Sin embargo, para hacer un mejor uso de tu monedero, configura un nombre de usuario en los ajustes de Telegram. Luego, introduce /balance para que el bot pueda actualizar su registro de ti."""
|
||||
|
||||
# BALANCE
|
||||
|
||||
balanceMessage = """👑 *Tu saldo:* %d sat"""
|
||||
balanceErrorMessage = """🚫 No se ha podido recuperar tu saldo. Por favor, inténtalo más tarde."""
|
||||
|
||||
# TIP
|
||||
|
||||
tipDidYouReplyMessage = """¿Has respondido a un mensaje para dar un tip? Para responder a cualquier mensaje, haz clic con el botón derecho del ratón -> Responder en tu ordenador o desliza el mensaje en tu teléfono. Si quieres enviar directamente a otro usuario, utiliza el comando /send."""
|
||||
tipInviteGroupMessage = """ℹ️ Por cierto, puedes invitar a este bot a cualquier grupo para empezar a dar tips allí."""
|
||||
tipEnterAmountMessage = """¿Ingresaste un monto?"""
|
||||
tipValidAmountMessage = """¿Ingresaste un monto válido?"""
|
||||
tipYourselfMessage = """📖 No te puedes dar tips a ti mismo."""
|
||||
tipSentMessage = """💸 %d sat enviado a %s."""
|
||||
tipReceivedMessage = """🏅 %s te ha dado un tip de %d sat."""
|
||||
tipErrorMessage = """🚫 El tip ha fallado."""
|
||||
tipUndefinedErrorMsg = """por favor, inténtalo más tarde."""
|
||||
tipHelpText = """📖 Oops, eso no funcionó. %s
|
||||
|
||||
*Uso:* `/tip <monto> [<memo>]`
|
||||
*Ejemplo:* `/tip 1000 ¡Meme de mal gusto!`"""
|
||||
|
||||
# SEND
|
||||
|
||||
sendValidAmountMessage = """¿Ingresaste un monto válido?"""
|
||||
sendUserHasNoWalletMessage = """🚫 El usuario %s aún no ha creado un monedero."""
|
||||
sendSentMessage = """💸 %d sat enviado a %s."""
|
||||
sendPublicSentMessage = """💸 %d sat enviado(s) de %s a %s."""
|
||||
sendReceivedMessage = """🏅 %s te envió %d sat."""
|
||||
sendErrorMessage = """🚫 Envío fallido."""
|
||||
confirmSendMessage = """¿Desea pagar a %s?\n\n💸 Monto: %d sat"""
|
||||
confirmSendAppendMemo = """\n✉️ %s"""
|
||||
sendCancelledMessage = """🚫 Envío cancelado."""
|
||||
errorTryLaterMessage = """🚫 Error. Por favor, inténtelo de nuevo más tarde."""
|
||||
sendSyntaxErrorMessage = """¿Has introducido un monto y un destinatario? Puedes utilizar el comando /send para enviar a usuarios de Telegram como %s o a una dirección Lightning como LightningTipBot@ln.tips."""
|
||||
sendHelpText = """📖 Oops, eso no funcionó. %s
|
||||
|
||||
*Uso:* `/send <monto> <usuario> [<memo>]`
|
||||
*Ejemplo:* `/send 1000 @LightningTipBot Me gusta el bot ❤️`.
|
||||
*Ejemplo:* `/send 1234 LightningTipBot@ln.tips`"""
|
||||
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Recibiste %d sat."""
|
||||
invoiceEnterAmountMessage = """¿Ingresaste un monto?"""
|
||||
invoiceValidAmountMessage = """¿Ingresaste un monto válido?"""
|
||||
invoiceHelpText = """📖 Oops, eso no funcionó. %s
|
||||
|
||||
*Uso:* `/invoice <monto> [<memo>]`
|
||||
*Ejemplo:* `/invoice 1000 ¡Gracias!`"""
|
||||
|
||||
# PAY
|
||||
|
||||
paymentCancelledMessage = """🚫 Pago cancelado."""
|
||||
invoicePaidMessage = """⚡️ Pago enviado."""
|
||||
invoicePublicPaidMessage = """⚡️ Pago enviado por %s."""
|
||||
invalidInvoiceHelpMessage = """¿Has introducido una factura Lightning válida? Prueba con /send si quieres enviar a un usuario de Telegram o a una dirección Lightning."""
|
||||
invoiceNoAmountMessage = """🚫 No se pueden pagar las facturas sin un monto."""
|
||||
insufficientFundsMessage = """🚫 Fondos insuficientes. Tienes %d sat pero necesitas al menos %d sat."""
|
||||
feeReserveMessage = """⚠️ El envío de todo el saldo puede fallar debido a las tarifas de la red. Si falla, intenta enviar un poco menos."""
|
||||
invoicePaymentFailedMessage = """🚫 Pago fallido: %s"""
|
||||
invoiceUndefinedErrorMessage = """No se pudo pagar la factura."""
|
||||
confirmPayInvoiceMessage = """¿Quieres enviar este pago?\n\n💸 Monto: %d sat"""
|
||||
confirmPayAppendMemo = """\n✉️ %s"""
|
||||
payHelpText = """📖 Oops, eso no funcionó. %s
|
||||
|
||||
*Uso:* `/pay <factura>`
|
||||
*Ejemplo:* `/pay lnbc20n1psscehd...`"""
|
||||
|
||||
# DONATE
|
||||
|
||||
donationSuccess = """🙏 Gracias por tu donación."""
|
||||
donationErrorMessage = """🚫 Oh, no. Donación fallida."""
|
||||
donationProgressMessage = """🧮 Preparando tu donación..."""
|
||||
donationFailedMessage = """🚫 Donación fallida: %s"""
|
||||
donateEnterAmountMessage = """¿Ingresaste un monto?"""
|
||||
donateValidAmountMessage = """¿Ingresaste un monto válido?"""
|
||||
donateHelpText = """📖 Oops, eso no funcionó. %s
|
||||
|
||||
*Uso:* `/donate <monto>`
|
||||
*Ejemplo:* `/donate 1000`"""
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 No se ha podido reconocer una factura Lightning o una LNURL. Intenta centrar el código QR, recortar la foto o ampliarla."""
|
||||
photoQrRecognizedMessage = """✅ QR code:
|
||||
`%s`"""
|
||||
|
||||
# LNURL
|
||||
|
||||
lnurlReceiveInfoText = """👇 Puedes usar esta LNURL estática para recibir pagos."""
|
||||
lnurlResolvingUrlMessage = """🧮 Solventando la dirección..."""
|
||||
lnurlGettingUserMessage = """🧮 Preparando el pago..."""
|
||||
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."""
|
||||
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*
|
||||
|
||||
⚠️ Nunca compartas la URL o el código QR con nadie o podrán acceder a tus fondos.
|
||||
|
||||
- *BlueWallet:* Pulse *Nuevo monedero*, *Importar monedero*, *Escanear o importar un archivo*, y escanea el código QR.
|
||||
- *Zeus:* Copia la URL de abajo, pulsa *Añadir un nuevo nodo*, *Importar* (la URL), *Guardar configuración del nodo*."""
|
||||
couldNotLinkMessage = """🚫 No se ha podido vincular su monedero. Por favor, inténtalo más tarde."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
inlineQueryFaucetTitle = """🚰 Crea un grifo."""
|
||||
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.
|
||||
|
||||
🚰 Restante: %d/%d sat (dado a %d/%d usuarios)
|
||||
%s"""
|
||||
inlineFaucetEndedMessage = """🚰 Grifo vacío 🍺\n\n🏅 %d sat dados a %d usuarios."""
|
||||
inlineFaucetAppendMemo = """\n✉️ %s"""
|
||||
inlineFaucetCreateWalletMessage = """Chatea con %s 👈 para gestionar tu cartera."""
|
||||
inlineFaucetCancelledMessage = """🚫 Grifo cancelado."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 El monto por usuario no es divisor de la capacidad."""
|
||||
inlineFaucetInvalidAmountMessage = """🚫 Monto inválido."""
|
||||
inlineFaucetSentMessage = """🚰 %d sat enviado(s) a %s."""
|
||||
inlineFaucetReceivedMessage = """🚰 %s te envió %d sat."""
|
||||
inlineFaucetHelpFaucetInGroup = """Crea un grifo en un grupo con el bot dentro o utiliza el 👉 comando _inline_ (/advanced para más)."""
|
||||
inlineFaucetHelpText = """📖 Oops, eso no funcionó. %s
|
||||
|
||||
*Uso:* `/faucet <capacidad> <por_usuario>`
|
||||
*Ejemplo:* `/faucet 210 21`"""
|
||||
|
||||
# INLINE SEND
|
||||
|
||||
inlineQuerySendTitle = """💸 Enviar el pago a un chat."""
|
||||
inlineQuerySendDescription = """Uso: @%s send <monto> [<usario>] [<memo>]"""
|
||||
inlineResultSendTitle = """💸 Enviar %d sat."""
|
||||
inlineResultSendDescription = """👉 Haga clic para enviar %d sat a este chat."""
|
||||
|
||||
inlineSendMessage = """Pulse ✅ para recibir el pago de %s.\n\n💸 Cantidad: %d sat"""
|
||||
inlineSendAppendMemo = """\n✉️ %s"""
|
||||
inlineSendUpdateMessageAccept = """💸 %d sat enviado de %s a %s."""
|
||||
inlineSendCreateWalletMessage = """Chatea con %s 👈 para gestionar tu cartera."""
|
||||
sendYourselfMessage = """📖 No puedes pagarte a ti mismo."""
|
||||
inlineSendFailedMessage = """🚫 Envío fallido."""
|
||||
inlineSendInvalidAmountMessage = """🚫 La cantidad debe ser mayor que 0."""
|
||||
inlineSendBalanceLowMessage = """🚫 Tu saldo es demasiado bajo."""
|
||||
|
||||
# INLINE RECEIVE
|
||||
|
||||
inlineQueryReceiveTitle = """🏅 Solicita un pago en un chat."""
|
||||
inlineQueryReceiveDescription = """Uso: @%s receive <monto> [<usario>] [<memo>]"""
|
||||
inlineResultReceiveTitle = """🏅 Recibir %d sat."""
|
||||
inlineResultReceiveDescription = """👉 Haga clic para solicitar un pago de %d sat."""
|
||||
|
||||
inlineReceiveMessage = """Pulsa 💸 para pagar a %s.\n\n💸 Monto: %d sat"""
|
||||
inlineReceiveAppendMemo = """\n✉️ %s"""
|
||||
inlineReceiveUpdateMessageAccept = """💸 %d sat enviado de %s a %s."""
|
||||
inlineReceiveCreateWalletMessage = """Chatea con %s 👈 para gestionar tu cartera."""
|
||||
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`"""
|
||||
@@ -0,0 +1,304 @@
|
||||
# COMMANDS
|
||||
|
||||
helpCommandStr = """Aide"""
|
||||
basicsCommandStr = """basics"""
|
||||
tipCommandStr = """tip"""
|
||||
balanceCommandStr = """Solde"""
|
||||
sendCommandStr = """Envoyer"""
|
||||
invoiceCommandStr = """invoice"""
|
||||
payCommandStr = """Payer"""
|
||||
donateCommandStr = """Donation"""
|
||||
advancedCommandStr = """Avancée"""
|
||||
transactionsCommandStr = """Transactions"""
|
||||
logCommandStr = """log"""
|
||||
listCommandStr = """list"""
|
||||
|
||||
linkCommandStr = """link"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """faucet"""
|
||||
|
||||
tipjarCommandStr = """tipjar"""
|
||||
receiveCommandStr = """Recevoir"""
|
||||
hideCommandStr = """masquer"""
|
||||
volcanoCommandStr = """volcano"""
|
||||
showCommandStr = """montrer"""
|
||||
optionsCommandStr = """options"""
|
||||
settingsCommandStr = """réglages"""
|
||||
saveCommandStr = """sauvegarder"""
|
||||
deleteCommandStr = """supprimer"""
|
||||
infoCommandStr = """info"""
|
||||
|
||||
# NOTIFICATIONS
|
||||
|
||||
cantDoThatMessage = """Vous ne pouvez pas faire ça."""
|
||||
cantClickMessage = """Ce bouton n'est pas cliquable."""
|
||||
balanceTooLowMessage = """Votre solde est trop bas."""
|
||||
|
||||
# BUTTONS
|
||||
|
||||
sendButtonMessage = """✅ Envoyer"""
|
||||
payButtonMessage = """✅ Payer"""
|
||||
payReceiveButtonMessage = """💸 Payé"""
|
||||
receiveButtonMessage = """✅ Reçu"""
|
||||
cancelButtonMessage = """🚫 Annuler"""
|
||||
collectButtonMessage = """✅ Collect"""
|
||||
nextButtonMessage = """Suivant"""
|
||||
backButtonMessage = """Précédent"""
|
||||
acceptButtonMessage = """Accepter"""
|
||||
denyButtonMessage = """Refuser"""
|
||||
tipButtonMessage = """Tip"""
|
||||
revealButtonMessage = """Révéler"""
|
||||
showButtonMessage = """Afficher"""
|
||||
hideButtonMessage = """Masquer"""
|
||||
joinButtonMessage = """Joindre"""
|
||||
optionsButtonMessage = """Options"""
|
||||
settingsButtonMessage = """Réglages"""
|
||||
saveButtonMessage = """Sauvegarder"""
|
||||
deleteButtonMessage = """Supprimer"""
|
||||
infoButtonMessage = """Info"""
|
||||
|
||||
# AIDE
|
||||
|
||||
helpMessage = """⚡️ *Wallet*
|
||||
_Ce bot est un Bitcoin Lightning wallet qui permet d'envoyer des pourboires sur Telegram. Pour envoyer des pourboires, ajoutez le bot à un groupe. L'unité de base des pourboires est les Satoshis (sat). 100,000,000 sat = 1 Bitcoin. Tapez 📚 /basics pour plus d'info._
|
||||
|
||||
❤️ *Donation*
|
||||
_Ce bot ne vous facture pas de frais mais nous coûte des Satoshis à opérerer. Si vous aimez ce bot, n'hésitez pas à faire un don pour soutenir le développement. Pour donner, utilisez_ `/donate 1000`
|
||||
|
||||
%s
|
||||
|
||||
⚙️ *Commandes*
|
||||
*/tip* 🏅 Répondre à un message pour envoyer un pourboire : `/tip <montant> [<memo>]`
|
||||
*/balance* 👑 Afficher votre solde: `/balance`
|
||||
*/send* 💸 Envoyer un pourboire à un utilisateur: `/send <montant> @user ou user@ln.tips [<memo>]`
|
||||
*/invoice* ⚡️ Recevoir avec Lightning : `/invoice <montant> [<memo>]`
|
||||
*/pay* ⚡️ Payer avec Lightning : `/pay <invoice>`
|
||||
*/donate* ❤️ Faire une donation au projet : `/donate 1000`
|
||||
*/advanced* 🤖 Fonctionnalités avancées.
|
||||
*/help* 📖 Aide."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Info*"""
|
||||
infoYourLightningAddress = """Votre adresse Lightning est `%s`"""
|
||||
|
||||
basicsMessage = """🧡 *Bitcoin*
|
||||
_Bitcoin est la monnaie d'internet. Aucune authorité ne contrôle ce réseau décentralisé et accessible à tous. Bitcoin est une monnaie saine qui est rapide, fiable et plus inclusive que le système financier traditionnel._
|
||||
|
||||
🧮 *Économie*
|
||||
_La plus petite unité du Bitcoin est un Satoshis (sat). 100,000,000 sat = 1 Bitcoin. Il n'existe que 21 millions de Bitcoin. La valeur du Bitcoin fluctue tous les jours. Néanmoins, si vous vivez avec le standard du Bitcoin, 1 sat sera toujours égal à 1 sat._
|
||||
|
||||
⚡️ *Le Lightning Network*
|
||||
_Le Lightning Network est un protocole de paiement qui permet d'envoyer et de recevoir rapidement du Bitcoin, à moindre coût et sans grande consommation d'énergie. Ce réseau rend accessible Bitcoin à des milliards de personnes._
|
||||
|
||||
📲 *Lightning Wallets*
|
||||
_Vos fonds sur ce bot peuvent être envoyés à n'importe quel Lightning Wallet. Nous recommandons de télécharger sur votre téléphone les wallets suivant_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (non-custodial), ou_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(facile)_.
|
||||
|
||||
📄 *Logiciel libre*
|
||||
_Ce bot est gratuit et_ [libre de droits](https://github.com/LightningTipBot/LightningTipBot)_. Vous pouvez éxecuter le bot sur votre ordinateur et l'utiliser dans votre communauté._
|
||||
|
||||
✈️ *Telegram*
|
||||
_Ajoutez ce bot à un groupe Telegram pour envoyer des pourboires en répondant à des messages. Si vous faites de ce bot un adminstrateur d'un groupe, il va réorganiser les commandes pour plus de lisibilité._
|
||||
|
||||
🏛 *Conditions d'utilisation*
|
||||
_Ce bot n'assure pas la garde de vos fonds. Nous agissons toujours dans votre intérêt et nous sommes consciens de devoir faire des compromis en raison de l'absence de KYC. Les fonds de votre portefeuille sont aujourd'hui considérés comme une donation. Ne nous donnez pas tout votre argent. Ce bot est une version beta, faites attention s'il vous plaît. À utiliser à vos risques et périls._
|
||||
|
||||
❤️ *Donation*
|
||||
_Ce bot ne vous facture pas de frais mais coûte des Satoshis à opérer. Si vous aimez ce bot, n'hésitez pas à faire un don pour soutenir le développement. Pour donner, utilisez_ `/donate 1000`"""
|
||||
|
||||
helpNoUsernameMessage = """👋 Définissez un nom d'utilisateur sur Telegram afin d'utiliser ce bot."""
|
||||
|
||||
advancedMessage = """%s
|
||||
|
||||
👉 *Inline commands*
|
||||
*send* 💸 Envoyer des sats : `%s send <montant> [<utilisateur>] [<memo>]`
|
||||
*receive* 🏅 Demander un paiement : `... receive <montant> [<utilisateur>] [<memo>]`
|
||||
*faucet* 🚰 Créer un faucet: `... faucet <capacité> <par_utilisateur> [<memo>]`
|
||||
*tipjar* 🍯 Créer un tipjar: `... tipjar <capacité> <par_utilisateur> [<memo>]`
|
||||
|
||||
📖 Vous pouvez utiliser ces commandes dans tous les chats et même dans les conversations privées. Attendez une seconde après avoir tapé une commandé puis *click* sur le résultat, n'appuyez pas sur entrée.
|
||||
|
||||
⚙️ *Commandes avancées*
|
||||
*/link* 🔗 Lier votre wallet à [BlueWallet](https://bluewallet.io/) ou [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl recevoir ou payer: `/lnurl` ou `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Créer un faucet: `/faucet <capacité> <par_utilisateur>`
|
||||
*/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..."""
|
||||
startWalletCreatedMessage = """🧮 Wallet créé."""
|
||||
startWalletReadyMessage = """✅ *Votre wallet est prêt.*"""
|
||||
startWalletErrorMessage = """🚫 Erreur lors de la création de votre wallet. Essayez de nouveau."""
|
||||
startNoUsernameMessage = """☝️ Vous n'avez pas encore de nom d'utilisateur sur Telegram. Vous n'en n'avez pas besoin pour utiliser ce bot mais l'expérience utilisateur est meilleure avec un nom d'utilisateur. Créez un nom puis tapez /balance pour actualiser le bot."""
|
||||
|
||||
# BALANCE
|
||||
|
||||
balanceMessage = """👑 *Votre solde:* %d sat"""
|
||||
balanceErrorMessage = """🚫 Impossible de récupérer votre solde. Essayez à nouveau."""
|
||||
|
||||
# TIP
|
||||
|
||||
tipDidYouReplyMessage = """Avez-vous répondu à un message pour envoyer un pourboire ? Pour répondre à un message, faites un clic droit puis cliquez sur "répondre". Si vous voulez envoyer des fonds directement à un utilisateur, utilisez la commande /send ."""
|
||||
tipInviteGroupMessage = """ℹ️ Vous pouvez ajouter ce bot à n'importe quel groupe."""
|
||||
tipEnterAmountMessage = """Avez-vous choisi un montant ?"""
|
||||
tipValidAmountMessage = """Avez-vous choisi un montant correct ?"""
|
||||
tipYourselfMessage = """📖 Vous ne pouvez pas vous envoyer de pourboire."""
|
||||
tipSentMessage = """💸 %d sat envoyé à %s."""
|
||||
tipReceivedMessage = """🏅 %s vous a envoyé un pourboire de %d sat."""
|
||||
tipErrorMessage = """🚫 Erreur lors de l'envoi."""
|
||||
tipUndefinedErrorMsg = """réessayez s'il vous plaît."""
|
||||
tipHelpText = """📖 Oops, cela n'a pas fonctionné. %s
|
||||
|
||||
*Usage:* `/tip <montant> [<memo>]`
|
||||
*Exemple:* `/tip 1000 Dank meme!`"""
|
||||
|
||||
# SEND
|
||||
|
||||
sendValidAmountMessage = """Avez-vous choisi un montant correct ?"""
|
||||
sendUserHasNoWalletMessage = """🚫 L'utilisateur %s n'a pas encore crée de wallet."""
|
||||
sendSentMessage = """💸 %d sat envoyé à %s."""
|
||||
sendPublicSentMessage = """💸 %d sat envoyé de %s à %s."""
|
||||
sendReceivedMessage = """🏅 %s vous a envoyé %d sat."""
|
||||
sendErrorMessage = """🚫 Erreur lors de l'envoi."""
|
||||
confirmSendMessage = """Voulez-vous envoyer à %s?\n\n💸 Montant : %d sat"""
|
||||
confirmSendAppendMemo = """\n✉️ %s"""
|
||||
sendCancelledMessage = """🚫 Envoi annulé."""
|
||||
errorTryLaterMessage = """🚫 Erreur. Merci de réésayer."""
|
||||
sendSyntaxErrorMessage = """Avez-vous ajouté un montant et un destinataire ? Utilisez la commande /send pour envoyer à un utilisateur Telegram comme %s ou bien à une adresse Lightning comme LightningTipBot@ln.tips."""
|
||||
sendHelpText = """📖 Oops, cela n'a pas fonctionné. %s
|
||||
|
||||
*Usage:* `/send <montant> <utilisateur> [<memo>]`
|
||||
*Exemple:* `/send 1000 @LightningTipBot J'adore le bot ! ❤️`
|
||||
*Exemple:* `/send 1234 LightningTipBot@ln.tips`"""
|
||||
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Vous avez reçu %d sat."""
|
||||
invoiceEnterAmountMessage = """Avez-vous choisi un montant ?"""
|
||||
invoiceValidAmountMessage = """Avez-vous choisi un montant correct ?"""
|
||||
invoiceHelpText = """📖 Oops, cela n'a pas fonctionné. %s
|
||||
|
||||
*Usage:* `/invoice <montant> [<memo>]`
|
||||
*Exemple:* `/invoice 1000 Merci beaucoup !`"""
|
||||
|
||||
# PAY
|
||||
|
||||
paymentCancelledMessage = """🚫 Paiement annulé."""
|
||||
invoicePaidMessage = """⚡️ Paiement envoyé."""
|
||||
invoicePublicPaidMessage = """⚡️ Paiement envoyé par %s."""
|
||||
invalidInvoiceHelpMessage = """Avez-vous ajouté un Lightning invoice valide ? Essayez /send pour envoyer à un utilisateur Telegram ou à une adresse Lightning."""
|
||||
invoiceNoAmountMessage = """🚫 Vous ne pouvez pas payer une facture sans montant."""
|
||||
insufficientFundsMessage = """🚫 Fonds insuffisants. Vous avez %d sat et vous avez besoin d'un minimum de %d sat."""
|
||||
feeReserveMessage = """⚠️ Envoyer tous vos fonds peut ne pas fonctionner en raison de la nécessité de payer des frais de réseau. Si cela échoue, essayez d'envoyer un peu moins."""
|
||||
invoicePaymentFailedMessage = """🚫 Le paiement a échoué : %s"""
|
||||
invoiceUndefinedErrorMessage = """Impossible de payer la facture."""
|
||||
confirmPayInvoiceMessage = """Voulez-vous envoyer ce paiement ?\n\n💸 Montant: %d sat"""
|
||||
confirmPayAppendMemo = """\n✉️ %s"""
|
||||
payHelpText = """📖 Oops, cela n'a pas fonctionné. %s
|
||||
|
||||
*Usage:* `/pay <invoice>`
|
||||
*Exemple:* `/pay lnbc20n1psscehd...`"""
|
||||
|
||||
# DONATE
|
||||
|
||||
donationSuccess = """🙏 Merci pour votre donation !."""
|
||||
donationErrorMessage = """🚫 Oh non, le paiement de la donation a échoué."""
|
||||
donationProgressMessage = """🧮 Préparation de votre donation..."""
|
||||
donationFailedMessage = """🚫 Echec de la donation: %s"""
|
||||
donateEnterAmountMessage = """Avez-vous choisi un montant ?"""
|
||||
donateValidAmountMessage = """Avez-vous choisi un montant correct ?"""
|
||||
donateHelpText = """📖 Oops, cela n'a pas fonctionné. %s
|
||||
|
||||
*Usage:* `/donate <montant>`
|
||||
*Exemple:* `/donate 1000`"""
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 Impossible de reconnaître une facture Lightning ou un LNRUL. Essayez de centrer le QR code ou de zoomer."""
|
||||
photoQrRecognizedMessage = """✅ QR code:
|
||||
`%s`"""
|
||||
|
||||
# LNURL
|
||||
|
||||
lnurlReceiveInfoText = """👇 Vous ne pouvez pas utiliser cet LNURL pour recevoir des paiements."""
|
||||
lnurlResolvingUrlMessage = """🧮 Recherche de l'adresse..."""
|
||||
lnurlGettingUserMessage = """🧮 Préparation du paiement..."""
|
||||
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."""
|
||||
lnurlHelpText = """📖 Oops, cela n'a pas fonctionné. %s
|
||||
|
||||
*Usage:* `/lnurl [montant] <lnurl>`
|
||||
*Exemple:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Lier votre wallet*
|
||||
|
||||
⚠️ Ne partagez jamais cet URL ou ce QR code au risque de donner accès à vos fonds à un tiers.
|
||||
|
||||
- *BlueWallet:* Appuyez sur *New wallet*, *Import wallet*, *Scan or import a file*, puis scanner le QR code.
|
||||
- *Zeus:* Copier l'URL, appuyez sur *Add a new node*, *Import* (l'URL), *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Impossible de lier votre wallet. Merci de réésayer."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
inlineQueryFaucetTitle = """🚰 Création d'un faucet."""
|
||||
inlineQueryFaucetDescription = """Usage: @%s faucet <capacité> <par_utilisateur>"""
|
||||
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.
|
||||
|
||||
🚰 Restant: %d/%d sat (envoyé à %d/%d utilisateurs)
|
||||
%s"""
|
||||
inlineFaucetEndedMessage = """🚰 Faucet vide 🍺\n\n🏅 %d sat envoyé à %d utilisateurs."""
|
||||
inlineFaucetAppendMemo = """\n✉️ %s"""
|
||||
inlineFaucetCreateWalletMessage = """Chat avec %s 👈 pour gérer votre wallet."""
|
||||
inlineFaucetCancelledMessage = """🚫 Faucet annulé."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 Le montant de l'utilisateur n'est pas suffisament divisdable."""
|
||||
inlineFaucetInvalidAmountMessage = """🚫 Montant incorrect."""
|
||||
inlineFaucetSentMessage = """🚰 %d sat envoyé à %s."""
|
||||
inlineFaucetReceivedMessage = """🚰 %s vous a envoyé %d sat."""
|
||||
inlineFaucetHelpFaucetInGroup = """Créez un faucet dans un groupe avec le bot ou utilisez 👉 les commandes (/advanced pour plus)."""
|
||||
inlineFaucetHelpText = """📖 Oops, cela n'a pas fonctionné. %s
|
||||
|
||||
*Usage:* `/faucet <capacité> <par_utilisateur>`
|
||||
*Exemple:* `/faucet 210 21`"""
|
||||
|
||||
# INLINE SEND
|
||||
|
||||
inlineQuerySendTitle = """💸 Envoyez des paiements dans un chat."""
|
||||
inlineQuerySendDescription = """Usage: @%s send <montant> [<utilisateur>] [<memo>]"""
|
||||
inlineResultSendTitle = """💸 Envoyé %d sat."""
|
||||
inlineResultSendDescription = """👉 Clique pour envoyer %d sat sur ce chat."""
|
||||
|
||||
inlineSendMessage = """Appuyez sur ✅ pour recevoir le paiement de %s.\n\n💸 Montant: %d sat"""
|
||||
inlineSendAppendMemo = """\n✉️ %s"""
|
||||
inlineSendUpdateMessageAccept = """💸 %d sat sent from %s to %s."""
|
||||
inlineSendCreateWalletMessage = """Chat avec %s 👈 pour gérer votre wallet."""
|
||||
sendYourselfMessage = """📖 Vous ne pouvez pas vous envoyer de pourboires."""
|
||||
inlineSendFailedMessage = """🚫 Echec de l'envoi."""
|
||||
inlineSendInvalidAmountMessage = """🚫 Le montant doit être supérieure à 0."""
|
||||
inlineSendBalanceLowMessage = """🚫 Votre solde est trop bas."""
|
||||
|
||||
# INLINE RECEIVE
|
||||
|
||||
inlineQueryReceiveTitle = """🏅 Demander un paiement dans un chat."""
|
||||
inlineQueryReceiveDescription = """Usage: @%s receive <montant> [<utilisateur>] [<memo>]"""
|
||||
inlineResultReceiveTitle = """🏅 Recevoir %d sat."""
|
||||
inlineResultReceiveDescription = """👉 Cliquez ici pour recevoir un paiement de %d sat."""
|
||||
|
||||
inlineReceiveMessage = """Appuyez sur 💸 pour payer %s.\n\n💸 Montant: %d sat"""
|
||||
inlineReceiveAppendMemo = """\n✉️ %s"""
|
||||
inlineReceiveUpdateMessageAccept = """💸 %d sat envoyé de %s à %s."""
|
||||
inlineReceiveCreateWalletMessage = """Chat avec %s 👈 pour gérer votre wallet."""
|
||||
inlineReceiveYourselfMessage = """📖 Vous ne pouvez pas vous envoyer de pourboires."""
|
||||
inlineReceiveFailedMessage = """🚫 La réception a échoué."""
|
||||
inlineReceiveCancelledMessage = """🚫 Réception annulée."""
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user