Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90ebd90d59 | ||
|
|
64c1bf1aa3 | ||
|
|
8d4b0a5f65 | ||
|
|
985952de00 | ||
|
|
3fe903bc51 | ||
|
|
4bf0e05d6c | ||
|
|
3317cf09e1 | ||
|
|
13759ff048 | ||
|
|
827bfb108d | ||
|
|
e2017ecfe9 | ||
|
|
059cb5cdd8 | ||
|
|
80d0ec57b1 | ||
|
|
790f0943cc | ||
|
|
4af2ca8799 | ||
|
|
323fd14c9e | ||
|
|
1002d323a1 | ||
|
|
d6f8380f4d |
@@ -29,7 +29,7 @@ After the configuration (see below), start it using the command
|
||||
|
||||
### Configuration
|
||||
|
||||
You need to edit `config.yaml` before you can start the bot.
|
||||
You need to edit `config.yaml` before starting 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 (reachable by the bot via `lnbits_url`).
|
||||
1. Create a wallet in LNbits (`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,53 +52,26 @@ 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 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).
|
||||
- `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).
|
||||
|
||||
## 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> <@user> or <user@domain.com> [<memo>]
|
||||
/invoice ⚡️ Receive over Lightning: /invoice <amount> [<memo>]
|
||||
/pay ⚡️ Pay over Lightning: /pay <invoice>
|
||||
/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>
|
||||
/help 📖 Read this help.
|
||||
/advanced 🤖 Read the advanced help.
|
||||
/basics 📚 More info.
|
||||
/donate ❤️ Donate to the project: /donate <amount>
|
||||
/info 📚 More info.
|
||||
/donate 🙏 Donate to @LightningTipBot: /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.
|
||||
@@ -107,18 +80,9 @@ 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 by the user's wallet (Tor should be fine as well).
|
||||
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.
|
||||
|
||||
<p align="center">
|
||||
<img alt="QR code payment example." src="resources/lndhub.png" >
|
||||
@@ -142,4 +106,3 @@ 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
@@ -0,0 +1,38 @@
|
||||
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
@@ -0,0 +1,41 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
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,12 +6,10 @@
|
||||
4 - Paste this:
|
||||
|
||||
help - Read the help.
|
||||
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
|
||||
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
|
||||
advanced - Advanced help
|
||||
@@ -0,0 +1,22 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
+9
-17
@@ -1,17 +1,9 @@
|
||||
bot:
|
||||
http_proxy: ""
|
||||
lnurl_public_host_name: "mylnurl.com"
|
||||
lnurl_server: "https://mylnurl.com"
|
||||
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"
|
||||
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
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
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,18 +1,15 @@
|
||||
package telegram
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
// PLEASE DO NOT CHANGE THE CODE IN THIS FILE
|
||||
@@ -21,70 +18,84 @@ import (
|
||||
// IF YOU USE THIS PROJECT, LEAVE THIS CODE ALONE
|
||||
|
||||
var (
|
||||
donationEndpoint string
|
||||
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 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) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
}
|
||||
// if no amount is in the command, ask for it
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
|
||||
// // no amount was entered, set user state and ask for amount
|
||||
bot.askForAmount(ctx, "", "CreateDonationState", 0, 0, m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// command is valid
|
||||
msg := bot.trySendMessage(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
|
||||
}
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
bot.tryEditMessage(msg, Translate(ctx, "donationSuccess"))
|
||||
|
||||
}
|
||||
|
||||
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()
|
||||
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 {
|
||||
@@ -112,17 +123,17 @@ func (rot13 rot13Reader) Read(b []byte) (int, error) {
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (bot TipBot) parseCmdDonHandler(ctx context.Context, m *tb.Message) error {
|
||||
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 {
|
||||
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 {
|
||||
if arg != "@"+bot.telegram.Me.Username {
|
||||
return fmt.Errorf("err")
|
||||
}
|
||||
}
|
||||
@@ -136,15 +147,15 @@ func (bot TipBot) parseCmdDonHandler(ctx context.Context, m *tb.Message) error {
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
_, err = io.Copy(&sb, rot13Reader{strings.NewReader("Gunax lbh! V'z ebhgvat guvf qbangvba gb YvtugavatGvcObg@ya.gvcf.")})
|
||||
_, err = io.Copy(&sb, rot13Reader{strings.NewReader("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.trySendMessage(m.Sender, str.MarkdownEscape(donationInterceptMessage))
|
||||
bot.telegram.Send(m.Sender, donationInterceptMessage)
|
||||
m.Text = fmt.Sprintf("/donate %d", amount)
|
||||
bot.donationHandler(ctx, m)
|
||||
bot.donationHandler(m)
|
||||
// returning nil here will abort the parent handler (/pay or /tip)
|
||||
return nil
|
||||
}
|
||||
@@ -3,27 +3,15 @@ module github.com/LightningTipBot/LightningTipBot
|
||||
go 1.15
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v0.3.1
|
||||
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/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/sirupsen/logrus v1.2.0
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||
github.com/tidwall/buntdb v1.2.7
|
||||
github.com/tidwall/gjson v1.10.2
|
||||
golang.org/x/text v0.3.5
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0
|
||||
gopkg.in/lightningtipbot/telebot.v2 v2.4.2-0.20211217193303-c005cce171ac
|
||||
gopkg.in/tucnak/telebot.v2 v2.3.5
|
||||
gorm.io/driver/sqlite v1.1.4
|
||||
gorm.io/gorm v1.21.12
|
||||
)
|
||||
|
||||
// replace gopkg.in/lightningtipbot/telebot.v2 => ../telebot
|
||||
|
||||
@@ -1,49 +1,19 @@
|
||||
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=
|
||||
@@ -84,177 +54,48 @@ github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg
|
||||
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/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=
|
||||
@@ -267,18 +108,8 @@ 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=
|
||||
@@ -287,17 +118,12 @@ 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=
|
||||
@@ -319,444 +145,138 @@ 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/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/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/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/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/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/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/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=
|
||||
@@ -764,14 +284,3 @@ 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=
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
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
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
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:"-"`
|
||||
}
|
||||
|
||||
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 + "/"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
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 MigrateAnonIdHash(db *gorm.DB) error {
|
||||
users := []lnbits.User{}
|
||||
_ = db.Find(&users)
|
||||
for _, u := range users {
|
||||
log.Info(u.ID, str.Int32Hash(u.ID))
|
||||
u.AnonID = fmt.Sprint(str.Int32Hash(u.ID))
|
||||
tx := db.Save(u)
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[MigrateAnonIdHash] Error: Couldn't migrate user %s (%d)", u.Telegram.Username, u.Telegram.ID)
|
||||
log.Errorln(errmsg)
|
||||
return tx.Error
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package errors
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
type TipBotErrorType int
|
||||
|
||||
const (
|
||||
DecodeAmountError TipBotErrorType = 1000 + iota
|
||||
DecodePerUserAmountError
|
||||
InvalidAmountError
|
||||
InvalidAmountPerUserError
|
||||
GetBalanceError
|
||||
BalanceToLowError
|
||||
)
|
||||
|
||||
func New(code TipBotErrorType, err error) TipBotError {
|
||||
return TipBotError{Err: err, Message: err.Error(), Code: 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)
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
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,17 +2,12 @@ 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",
|
||||
@@ -79,18 +74,14 @@ 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 (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))
|
||||
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))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -108,13 +99,8 @@ func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx BitInvoice, err e
|
||||
|
||||
// Info returns wallet information
|
||||
func (c Client) Info(w Wallet) (wtx Wallet, err error) {
|
||||
// custom header with invoice key
|
||||
invoiceHeader := req.Header{
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"X-Api-Key": w.Inkey,
|
||||
}
|
||||
resp, err := req.Get(c.url+"/api/v1/wallet", invoiceHeader, nil)
|
||||
c.header["X-Api-Key"] = w.Adminkey
|
||||
resp, err := req.Get(w.url+"/api/v1/wallet", w.header, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -149,16 +135,9 @@ func (c Client) Wallets(w User) (wtx []Wallet, err error) {
|
||||
}
|
||||
|
||||
// Pay pays a given invoice with funds from the wallet.
|
||||
func (w Wallet) Pay(params PaymentParams, c *Client) (wtx BitInvoice, err error) {
|
||||
// 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))
|
||||
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))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
+23
-26
@@ -1,10 +1,8 @@
|
||||
package lnbits
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/imroc/req"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
@@ -22,42 +20,24 @@ type User struct {
|
||||
Wallet *Wallet `gorm:"embedded;embeddedPrefix:wallet_"`
|
||||
StateKey UserStateKey `json:"stateKey"`
|
||||
StateData string `json:"stateData"`
|
||||
CreatedAt time.Time `json:"created"`
|
||||
UpdatedAt time.Time `json:"updated"`
|
||||
AnonID string `jsin:"anonid"`
|
||||
}
|
||||
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"` // must be True if invoice is payed, False if invoice is received
|
||||
Amount int64 `json:"amount"` // amount in MilliSatoshi
|
||||
Memo string `json:"memo,omitempty"` // the invoice memo.
|
||||
Webhook string `json:"webhook,omitempty"` // the webhook to fire back to when payment is received.
|
||||
DescriptionHash string `json:"description_hash,omitempty"` // the invoice description hash.
|
||||
Out bool `json:"out"`
|
||||
Amount int64 `json:"amount"`
|
||||
Memo string `json:"memo"` // the invoice description.
|
||||
Webhook string `json:"webhook,omitempty"`
|
||||
}
|
||||
|
||||
type PaymentParams struct {
|
||||
@@ -90,6 +70,7 @@ func (err Error) Error() string {
|
||||
}
|
||||
|
||||
type Wallet struct {
|
||||
*Client `gorm:"-"`
|
||||
ID string `json:"id" gorm:"id"`
|
||||
Adminkey string `json:"adminkey"`
|
||||
Inkey string `json:"inkey"`
|
||||
@@ -101,3 +82,19 @@ 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"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
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)
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
package lnurl
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
type LNURLInvoice 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"`
|
||||
}
|
||||
|
||||
func (lnurlInvoice LNURLInvoice) Key() string {
|
||||
return fmt.Sprintf("lnurl-p:%s", lnurlInvoice.PaymentHash)
|
||||
}
|
||||
|
||||
func (w Server) handleLnUrl(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 == "" {
|
||||
NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Form value 'amount' is not set"))
|
||||
return
|
||||
}
|
||||
amount, parseError := strconv.Atoi(stringAmount)
|
||||
if parseError != nil {
|
||||
NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Couldn't cast amount to int %v", parseError))
|
||||
return
|
||||
}
|
||||
comment := request.FormValue("comment")
|
||||
if len(comment) > CommentAllowed {
|
||||
NotFoundHandler(writer, fmt.Errorf("[handleLnUrl] Comment is too long"))
|
||||
return
|
||||
}
|
||||
response, err = w.serveLNURLpSecond(username, int64(amount), comment)
|
||||
}
|
||||
// check if error was returned from first or second handlers
|
||||
if err != nil {
|
||||
// log the error
|
||||
log.Errorf("[LNURL] %v", err.Error())
|
||||
if response != nil {
|
||||
// there is a valid error response
|
||||
err = writeResponse(writer, response)
|
||||
if err != nil {
|
||||
NotFoundHandler(writer, err)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
// no error from first or second handler
|
||||
err = writeResponse(writer, response)
|
||||
if err != nil {
|
||||
NotFoundHandler(writer, err)
|
||||
}
|
||||
}
|
||||
|
||||
// serveLNURLpFirst serves the first part of the LNURLp protocol with the endpoint
|
||||
// to call and the metadata that matches the description hash of the second response
|
||||
func (w Server) serveLNURLpFirst(username string) (*lnurl.LNURLPayParams, error) {
|
||||
log.Infof("[LNURL] Serving endpoint for user %s", username)
|
||||
callbackURL, err := url.Parse(fmt.Sprintf("%s/%s/%s", w.callbackHostname.String(), lnurlEndpoint, username))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
metadata := w.metaData(username)
|
||||
|
||||
return &lnurl.LNURLPayParams{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: statusOk},
|
||||
Tag: payRequestTag,
|
||||
Callback: callbackURL.String(),
|
||||
MinSendable: minSendable,
|
||||
MaxSendable: MaxSendable,
|
||||
EncodedMetadata: metadata.Encode(),
|
||||
CommentAllowed: CommentAllowed,
|
||||
}, nil
|
||||
|
||||
}
|
||||
|
||||
// serveLNURLpSecond serves the second LNURL response with the payment request with the correct description hash
|
||||
func (w Server) serveLNURLpSecond(username string, amount_msat int64, comment string) (*lnurl.LNURLPayValues, error) {
|
||||
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: statusError,
|
||||
Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", minSendable, MaxSendable)},
|
||||
}, fmt.Errorf("amount out of bounds")
|
||||
}
|
||||
// check comment length
|
||||
if len(comment) > CommentAllowed {
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: statusError,
|
||||
Reason: fmt.Sprintf("Comment too long (max: %d characters).", CommentAllowed)},
|
||||
}, fmt.Errorf("comment too long")
|
||||
}
|
||||
|
||||
// now check for the user
|
||||
user := &lnbits.User{}
|
||||
// check if "username" is actually the user ID
|
||||
tx := w.database
|
||||
if _, err := strconv.ParseInt(username, 10, 64); err == nil {
|
||||
// asume it's a user ID
|
||||
tx = w.database.Where("anon_id = ?", username).First(user)
|
||||
} else {
|
||||
// assume it's a string @username
|
||||
tx = w.database.Where("telegram_username = ? COLLATE NOCASE", username).First(user)
|
||||
}
|
||||
|
||||
if tx.Error != nil {
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: statusError,
|
||||
Reason: fmt.Sprintf("Invalid user.")},
|
||||
}, fmt.Errorf("[GetUser] Couldn't fetch user info from database: %v", tx.Error)
|
||||
}
|
||||
if user.Wallet == nil {
|
||||
return &lnurl.LNURLPayValues{
|
||||
LNURLResponse: lnurl.LNURLResponse{
|
||||
Status: statusError,
|
||||
Reason: fmt.Sprintf("Invalid user.")},
|
||||
}, fmt.Errorf("[serveLNURLpSecond] user %s not found", username)
|
||||
}
|
||||
// user is ok now create invoice
|
||||
// set wallet lnbits client
|
||||
|
||||
var resp *lnurl.LNURLPayValues
|
||||
|
||||
// the same description_hash needs to be built in the second request
|
||||
metadata := w.metaData(username)
|
||||
descriptionHash, err := w.descriptionHash(metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Amount: amount_msat / 1000,
|
||||
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: 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 metdata for a notification when paid)
|
||||
runtime.IgnoreError(w.buntdb.Set(
|
||||
LNURLInvoice{
|
||||
Invoice: invoiceStruct,
|
||||
User: user,
|
||||
Comment: comment,
|
||||
CreatedAt: time.Now(),
|
||||
}))
|
||||
// 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: 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 Server) descriptionHash(metadata lnurl.Metadata) (string, error) {
|
||||
hash := sha256.Sum256([]byte(metadata.Encode()))
|
||||
hashString := hex.EncodeToString(hash[:])
|
||||
return hashString, nil
|
||||
}
|
||||
|
||||
// metaData returns the metadata that is sent in the first response
|
||||
// and is used again in the second response to verify the description hash
|
||||
func (w Server) metaData(username string) lnurl.Metadata {
|
||||
return lnurl.Metadata{
|
||||
Description: fmt.Sprintf("Pay to %s@%s", username, w.callbackHostname.Hostname()),
|
||||
LightningAddress: fmt.Sprintf("%s@%s", username, w.callbackHostname.Hostname()),
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package lnurl
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
httpServer *http.Server
|
||||
bot *telegram.TipBot
|
||||
c *lnbits.Client
|
||||
database *gorm.DB
|
||||
callbackHostname *url.URL
|
||||
buntdb *storage.DB
|
||||
WebhookServer string
|
||||
}
|
||||
|
||||
const (
|
||||
statusError = "ERROR"
|
||||
statusOk = "OK"
|
||||
payRequestTag = "payRequest"
|
||||
lnurlEndpoint = ".well-known/lnurlp"
|
||||
minSendable = 1000 // mSat
|
||||
MaxSendable = 1_000_000_000
|
||||
CommentAllowed = 500
|
||||
)
|
||||
|
||||
func NewServer(bot *telegram.TipBot) *Server {
|
||||
srv := &http.Server{
|
||||
Addr: internal.Configuration.Bot.LNURLServerUrl.Host,
|
||||
// Good practice: enforce timeouts for servers you create!
|
||||
WriteTimeout: 15 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
}
|
||||
apiServer := &Server{
|
||||
c: bot.Client,
|
||||
database: bot.Database,
|
||||
bot: bot,
|
||||
httpServer: srv,
|
||||
callbackHostname: internal.Configuration.Bot.LNURLHostUrl,
|
||||
WebhookServer: internal.Configuration.Lnbits.WebhookServer,
|
||||
buntdb: bot.Bunt,
|
||||
}
|
||||
|
||||
apiServer.httpServer.Handler = apiServer.newRouter()
|
||||
go apiServer.httpServer.ListenAndServe()
|
||||
log.Infof("[LNURL] Server started at %s", internal.Configuration.Bot.LNURLServerUrl.Host)
|
||||
return apiServer
|
||||
}
|
||||
|
||||
func (w *Server) newRouter() *mux.Router {
|
||||
router := mux.NewRouter()
|
||||
router.HandleFunc("/.well-known/lnurlp/{username}", w.handleLnUrl).Methods(http.MethodGet)
|
||||
router.HandleFunc("/@{username}", w.handleLnUrl).Methods(http.MethodGet)
|
||||
return router
|
||||
}
|
||||
|
||||
func NotFoundHandler(writer http.ResponseWriter, err error) {
|
||||
log.Errorln(err)
|
||||
// return 404 on any error
|
||||
http.Error(writer, "404 page not found", http.StatusNotFound)
|
||||
}
|
||||
|
||||
func writeResponse(writer http.ResponseWriter, response interface{}) error {
|
||||
jsonResponse, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = writer.Write(jsonResponse)
|
||||
return err
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
package rate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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.25), 20)
|
||||
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 *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 {
|
||||
idLimiter.GetLimiter(id).Wait(context.Background())
|
||||
}
|
||||
}
|
||||
|
||||
// Add creates a new rate limiter and adds it to the keys map,
|
||||
// using the key
|
||||
func (i *Limiter) Add(key string) *rate.Limiter {
|
||||
i.mu.Lock()
|
||||
defer i.mu.Unlock()
|
||||
|
||||
limiter := rate.NewLimiter(i.r, i.b)
|
||||
|
||||
i.keys[key] = limiter
|
||||
|
||||
return limiter
|
||||
}
|
||||
|
||||
// GetLimiter returns the rate limiter for the provided key if it exists.
|
||||
// Otherwise, calls Add to add key address to the map
|
||||
func (i *Limiter) GetLimiter(key string) *rate.Limiter {
|
||||
i.mu.Lock()
|
||||
limiter, exists := i.keys[key]
|
||||
|
||||
if !exists {
|
||||
i.mu.Unlock()
|
||||
return i.Add(key)
|
||||
}
|
||||
|
||||
i.mu.Unlock()
|
||||
|
||||
return limiter
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
"time"
|
||||
)
|
||||
|
||||
var tickerMap cmap.ConcurrentMap
|
||||
|
||||
func init() {
|
||||
tickerMap = cmap.New()
|
||||
}
|
||||
|
||||
var defaultTickerCoolDown = time.Second * 10
|
||||
|
||||
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
|
||||
type ResettableFunctionTicker struct {
|
||||
Ticker *time.Ticker
|
||||
ResetChan chan struct{} // channel used to reset the ticker
|
||||
duration time.Duration
|
||||
Started bool
|
||||
name string
|
||||
}
|
||||
type ResettableFunctionTickerOption func(*ResettableFunctionTicker)
|
||||
|
||||
func WithDuration(d time.Duration) ResettableFunctionTickerOption {
|
||||
return func(a *ResettableFunctionTicker) {
|
||||
a.duration = d
|
||||
}
|
||||
}
|
||||
func RemoveTicker(name string) {
|
||||
tickerMap.Remove(name)
|
||||
}
|
||||
func GetTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
|
||||
|
||||
if t, ok := tickerMap.Get(name); ok {
|
||||
return t.(*ResettableFunctionTicker)
|
||||
} else {
|
||||
t := NewResettableFunctionTicker(name, option...)
|
||||
tickerMap.Set(name, t)
|
||||
return t
|
||||
}
|
||||
}
|
||||
func NewResettableFunctionTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
|
||||
t := &ResettableFunctionTicker{
|
||||
ResetChan: make(chan struct{}, 1),
|
||||
name: name,
|
||||
}
|
||||
|
||||
for _, opt := range option {
|
||||
opt(t)
|
||||
}
|
||||
if t.duration == 0 {
|
||||
t.duration = defaultTickerCoolDown
|
||||
}
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *ResettableFunctionTicker) Do(f func()) {
|
||||
t.Started = true
|
||||
tickerMap.Set(t.name, t)
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-t.Ticker.C:
|
||||
// ticker delivered signal. do function f
|
||||
f()
|
||||
return
|
||||
case <-t.ResetChan:
|
||||
// reset signal received. creating new ticker.
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package mutex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var mutexMap cmap.ConcurrentMap
|
||||
|
||||
func init() {
|
||||
mutexMap = cmap.New()
|
||||
}
|
||||
|
||||
// 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)
|
||||
// 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)
|
||||
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)
|
||||
} 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()
|
||||
mutexMap.Set(s, m)
|
||||
} else {
|
||||
m := &sync.Mutex{}
|
||||
m.Lock()
|
||||
mutexMap.Set(s, m)
|
||||
}
|
||||
log.Tracef("[Mutex] Locked %s", s)
|
||||
}
|
||||
|
||||
// Unlock unlocks a mutex in the mutexMap.
|
||||
func Unlock(s string) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package once
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
cmap "github.com/orcaman/concurrent-map"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var onceMap cmap.ConcurrentMap
|
||||
|
||||
func init() {
|
||||
onceMap = cmap.New()
|
||||
}
|
||||
|
||||
func New(objectKey string) {
|
||||
onceMap.Set(objectKey, cmap.New())
|
||||
}
|
||||
|
||||
// Once creates a map of keys k1 with a map of keys k2.
|
||||
// The idea is that an object with ID k1 can create a list of users k2
|
||||
// that have already interacted with the object. If the user k2 is in the list,
|
||||
// the object is not allowed to accessed again.
|
||||
func Once(k1, k2 string) error {
|
||||
i, ok := onceMap.Get(k1)
|
||||
if ok {
|
||||
return setOrReturn(i.(cmap.ConcurrentMap), k2)
|
||||
}
|
||||
userMap := cmap.New()
|
||||
onceMap.Set(k1, userMap)
|
||||
log.Tracef("[Once] Added key %s to onceMap (len=%d)", k1, len(onceMap.Keys()))
|
||||
return setOrReturn(userMap, k2)
|
||||
}
|
||||
|
||||
// setOrReturn sets the key k2 in the map i if it is not already set.
|
||||
func setOrReturn(objectMap cmap.ConcurrentMap, k2 string) error {
|
||||
if _, ok := objectMap.Get(k2); ok {
|
||||
return fmt.Errorf("%s already consumed object", k2)
|
||||
}
|
||||
objectMap.Set(k2, true)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove removes the key k1 from the map. Should be called after Once was called and
|
||||
// the object k1 finished.
|
||||
func Remove(k1 string) {
|
||||
onceMap.Remove(k1)
|
||||
log.Tracef("[Once] Removed key %s from onceMap (len=%d)", k1, len(onceMap.Keys()))
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"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()
|
||||
return db.Delete(s.Key(), s)
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
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
|
||||
})
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package str
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
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()
|
||||
}
|
||||
@@ -1,231 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"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 "", errors.New("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, errors.New(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, errors.New("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, errors.New("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) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return // errors.New("user has no wallet"), 0
|
||||
}
|
||||
|
||||
if !(user.StateKey == lnbits.UserEnterAmount) {
|
||||
ResetUserState(user, bot)
|
||||
return // errors.New("user state does not match"), 0
|
||||
}
|
||||
|
||||
var EnterAmountStateData EnterAmountStateData
|
||||
err := json.Unmarshal([]byte(user.StateData), &EnterAmountStateData)
|
||||
if err != nil {
|
||||
log.Errorf("[enterAmountHandler] %s", err.Error())
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
}
|
||||
|
||||
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 //err, 0
|
||||
}
|
||||
// amount not in allowed range from LNURL
|
||||
if EnterAmountStateData.AmountMin > 0 && EnterAmountStateData.AmountMax >= EnterAmountStateData.AmountMin && // this line checks whether min_max is set at all
|
||||
(amount > int64(EnterAmountStateData.AmountMax/1000) || amount < int64(EnterAmountStateData.AmountMin/1000)) { // this line then checks whether the amount is in the range
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
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
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
|
||||
bot.lnurlPayHandlerSend(ctx, m)
|
||||
return
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(StateDataJson))
|
||||
bot.lnurlWithdrawHandlerWithdraw(ctx, m)
|
||||
return
|
||||
case "CreateInvoiceState":
|
||||
m.Text = fmt.Sprintf("/invoice %d", amount)
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
bot.invoiceHandler(ctx, m)
|
||||
return
|
||||
case "CreateDonationState":
|
||||
m.Text = fmt.Sprintf("/donate %d", amount)
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
bot.donationHandler(ctx, m)
|
||||
return
|
||||
case "CreateSendState":
|
||||
splits := strings.SplitAfterN(EnterAmountStateData.OiringalCommand, " ", 2)
|
||||
if len(splits) > 1 {
|
||||
m.Text = fmt.Sprintf("/send %d %s", amount, splits[1])
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, "")
|
||||
bot.sendHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
return
|
||||
default:
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
}
|
||||
// // reset database entry
|
||||
// ResetUserState(user, bot)
|
||||
// return
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot TipBot) balanceHandler(ctx context.Context, m *tb.Message) {
|
||||
// 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
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if !user.Initialized {
|
||||
bot.startHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
log.Infof("[/balance] %s's balance: %d sat\n", usrStr, balance)
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "balanceMessage"), balance))
|
||||
return
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// 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())
|
||||
}
|
||||
bot.registerTelegramHandlers()
|
||||
initInvoiceEventCallbacks(bot)
|
||||
initializeStateCallbackMessage(bot)
|
||||
bot.Telegram.Start()
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
|
||||
// we can't use space in the label of buttons, because string splitting will mess everything up.
|
||||
const (
|
||||
CommandSend = "💸 Send"
|
||||
CommandBalance = "👑 Balance"
|
||||
CommandInvoice = "⚡️ Invoice"
|
||||
CommandHelp = "📖 Help"
|
||||
)
|
||||
|
||||
var (
|
||||
mainMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnHelpMainMenu = mainMenu.Text(CommandHelp)
|
||||
btnSendMainMenu = mainMenu.Text(CommandSend)
|
||||
btnBalanceMainMenu = mainMenu.Text(CommandBalance)
|
||||
btnInvoiceMainMenu = mainMenu.Text(CommandInvoice)
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"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
|
||||
if !db.Migrator().HasColumn(&lnbits.User{}, "anon_id") {
|
||||
// first we need to auto migrate the user. This will create anon_id column
|
||||
err = db.AutoMigrate(&lnbits.User{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.Info("Running ano_id database migrations ...")
|
||||
// run the migration on anon_id
|
||||
err = database.MigrateAnonIdHash(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 UpdateUserRecord(user *lnbits.User, bot TipBot) error {
|
||||
user.UpdatedAt = time.Now()
|
||||
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))
|
||||
if bot.Cache.GoCacheStore != nil {
|
||||
updateCachedUser(user, bot)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot *TipBot) fileHandler(ctx context.Context, m *tb.Message) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return
|
||||
}
|
||||
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, 0)
|
||||
runtime.RemoveTicker(user.ID)
|
||||
})
|
||||
} else {
|
||||
ticker.ResetChan <- struct{}{}
|
||||
}
|
||||
|
||||
c(ctx, m)
|
||||
return
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,86 +0,0 @@
|
||||
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) {
|
||||
// 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
|
||||
}
|
||||
|
||||
func (bot TipBot) basicsHandler(ctx context.Context, m *tb.Message) {
|
||||
// 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
|
||||
}
|
||||
|
||||
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) {
|
||||
// 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
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,392 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/once"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
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")
|
||||
)
|
||||
|
||||
const idTemplate = "faucet-%d-%d-%s"
|
||||
|
||||
type Faucet struct {
|
||||
*storage.Base
|
||||
Message string `json:"faucet_message"`
|
||||
Amount int64 `json:"faucet_amount"`
|
||||
RemainingAmount int64 `json:"faucet_remainingamount"`
|
||||
PerUserAmount int64 `json:"faucet_peruseramount"`
|
||||
From *lnbits.User `json:"faucet_from"`
|
||||
To []*lnbits.User `json:"faucet_to"`
|
||||
Memo string `json:"faucet_memo"`
|
||||
NTotal int `json:"faucet_ntotal"`
|
||||
NTaken int `json:"faucet_ntaken"`
|
||||
UserNeedsWallet bool `json:"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, inline bool, sender *tb.User) (*Faucet, 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, amount, amount, 0, nTotal, MakeProgressbar(amount, amount))
|
||||
if len(memo) > 0 {
|
||||
inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineFaucetAppendMemo"), memo)
|
||||
}
|
||||
|
||||
id := fmt.Sprintf(idTemplate, sender.ID, amount, RandStringRunes(5))
|
||||
if inline {
|
||||
id = fmt.Sprintf("inl-%s", id)
|
||||
}
|
||||
|
||||
return &Faucet{
|
||||
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) handleFaucetError(ctx context.Context, faucet interface{}, err error) {
|
||||
var m *tb.Message
|
||||
var q *tb.Query
|
||||
switch faucet.(type) {
|
||||
case *tb.Message:
|
||||
m = faucet.(*tb.Message)
|
||||
case *tb.Query:
|
||||
q = faucet.(*tb.Query)
|
||||
}
|
||||
switch err.(errors.TipBotError).Code {
|
||||
case errors.DecodeAmountError:
|
||||
if q != nil {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
} else if m != nil {
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
|
||||
case errors.DecodePerUserAmountError:
|
||||
if q != nil {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
} else if m != nil {
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), ""))
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
|
||||
case errors.InvalidAmountError:
|
||||
if q != nil {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
} else if m != nil {
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
|
||||
case errors.InvalidAmountPerUserError:
|
||||
if q != nil {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineFaucetInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
} else if m != nil {
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidPeruserAmountMessage")))
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
case errors.GetBalanceError:
|
||||
if q != nil {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
} else if m != nil {
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
case errors.BalanceToLowError:
|
||||
if q != nil {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
|
||||
} else if m != nil {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "inlineSendBalanceLowMessage"))
|
||||
bot.tryDeleteMessage(m)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func (bot TipBot) makeFaucetKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
|
||||
// inlineFaucetMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
acceptInlineFaucetButton := inlineFaucetMenu.Data(Translate(ctx, "collectButtonMessage"), "confirm_faucet_inline")
|
||||
cancelInlineFaucetButton := inlineFaucetMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_faucet_inline")
|
||||
acceptInlineFaucetButton.Data = id
|
||||
cancelInlineFaucetButton.Data = id
|
||||
inlineFaucetMenu.Inline(
|
||||
inlineFaucetMenu.Row(
|
||||
acceptInlineFaucetButton,
|
||||
cancelInlineFaucetButton),
|
||||
)
|
||||
return inlineFaucetMenu
|
||||
}
|
||||
|
||||
func (bot TipBot) createFaucetHandler(ctx context.Context, m *tb.Message) {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if m.Private() {
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetHelpFaucetInGroup")))
|
||||
return
|
||||
}
|
||||
ctx = bot.mapFaucetLanguage(ctx, m.Text)
|
||||
inlineFaucet, err := bot.createFaucet(ctx, m.Text, false, m.Sender)
|
||||
if err != nil {
|
||||
log.Warnf("[faucet] %s", err.Error())
|
||||
return
|
||||
}
|
||||
fromUserStr := GetUserStr(m.Sender)
|
||||
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)
|
||||
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
|
||||
}
|
||||
|
||||
func (bot TipBot) createInlineFaucetHandler(ctx context.Context, q *tb.Query) {
|
||||
inlineFaucet, err := bot.createFaucet(ctx, q.Text, true, &q.From)
|
||||
if err != nil {
|
||||
bot.handleFaucetError(ctx, q, err)
|
||||
log.Errorf("[createInlineFaucetHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
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())
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptFaucetHandler(ctx context.Context, c *tb.Callback) {
|
||||
to := LoadUser(ctx)
|
||||
tx := &Faucet{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("[acceptFaucetHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
inlineFaucet := fn.(*Faucet)
|
||||
from := inlineFaucet.From
|
||||
// log faucet link if possible
|
||||
if c.Message != nil && c.Message.Chat != nil {
|
||||
log.Debugf("[faucet] Link: https://t.me/c/%s/%d", strconv.FormatInt(c.Message.Chat.ID, 10)[4:], c.Message.ID)
|
||||
}
|
||||
if !inlineFaucet.Active {
|
||||
log.Debugf(fmt.Sprintf("[faucet] faucet %s inactive. Remaining: %d sat", inlineFaucet.ID, inlineFaucet.RemainingAmount))
|
||||
bot.finishFaucet(ctx, c, inlineFaucet)
|
||||
return
|
||||
}
|
||||
// release faucet no matter what
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
log.Debugf("[faucet] %s is the owner faucet %s", GetUserStr(to.Telegram), inlineFaucet.ID)
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return
|
||||
}
|
||||
// check if to user has already taken from the faucet
|
||||
for _, a := range inlineFaucet.To {
|
||||
if a.Telegram.ID == to.Telegram.ID {
|
||||
// to user is already in To slice, has taken from facuet
|
||||
log.Debugf("[faucet] %s:%d already took from faucet %s", GetUserStr(to.Telegram), to.Telegram.ID, inlineFaucet.ID)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
// if faucet fails, cancel it:
|
||||
// c.Sender.ID = inlineFaucet.From.Telegram.ID // overwrite the sender of the callback to be the faucet owner
|
||||
// log.Debugf("[faucet] Canceling faucet %s...", inlineFaucet.ID)
|
||||
// bot.cancelInlineFaucet(ctx, c, true) // cancel without ID check
|
||||
return
|
||||
}
|
||||
|
||||
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() {
|
||||
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineFaucetReceivedMessage"), fromUserStrMd, inlineFaucet.PerUserAmount))
|
||||
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineFaucetSentMessage"), inlineFaucet.PerUserAmount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[faucet] Error: Send message to %s: %s", toUserStr, err.Error())
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
}()
|
||||
|
||||
// build faucet message
|
||||
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetMessage"), inlineFaucet.PerUserAmount, inlineFaucet.RemainingAmount, inlineFaucet.Amount, inlineFaucet.NTaken, inlineFaucet.NTotal, MakeProgressbar(inlineFaucet.RemainingAmount, inlineFaucet.Amount))
|
||||
memo := inlineFaucet.Memo
|
||||
if len(memo) > 0 {
|
||||
inlineFaucet.Message = inlineFaucet.Message + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetAppendMemo"), memo)
|
||||
}
|
||||
if inlineFaucet.UserNeedsWallet {
|
||||
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
// update message
|
||||
log.Infoln(inlineFaucet.Message)
|
||||
|
||||
// update the message if the faucet still has some sats left after this tx
|
||||
if inlineFaucet.RemainingAmount >= inlineFaucet.PerUserAmount {
|
||||
go func() {
|
||||
bot.tryEditMessage(c.Message, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
|
||||
}()
|
||||
}
|
||||
}
|
||||
if inlineFaucet.RemainingAmount < inlineFaucet.PerUserAmount {
|
||||
// faucet is depleted
|
||||
bot.finishFaucet(ctx, c, inlineFaucet)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineFaucet(ctx context.Context, c *tb.Callback, ignoreID bool) {
|
||||
tx := &Faucet{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
|
||||
}
|
||||
|
||||
inlineFaucet := fn.(*Faucet)
|
||||
if ignoreID || c.Sender.ID == inlineFaucet.From.Telegram.ID {
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineFaucet inactive
|
||||
inlineFaucet.Active = false
|
||||
inlineFaucet.Canceled = true
|
||||
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
|
||||
log.Debugf("[faucet] Faucet %s canceled.", inlineFaucet.ID)
|
||||
once.Remove(inlineFaucet.ID)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (bot *TipBot) finishFaucet(ctx context.Context, c *tb.Callback, inlineFaucet *Faucet) {
|
||||
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetEndedMessage"), inlineFaucet.Amount, inlineFaucet.NTaken)
|
||||
if inlineFaucet.UserNeedsWallet {
|
||||
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
}
|
||||
bot.tryEditMessage(c.Message, inlineFaucet.Message, &tb.ReplyMarkup{})
|
||||
inlineFaucet.Active = false
|
||||
log.Debugf("[faucet] Faucet finished %s", inlineFaucet.ID)
|
||||
once.Remove(inlineFaucet.ID)
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
|
||||
bot.cancelInlineFaucet(ctx, c, false)
|
||||
return
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
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) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
if q.Text == "" {
|
||||
bot.inlineQueryInstructions(ctx, q)
|
||||
return
|
||||
}
|
||||
|
||||
// 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") {
|
||||
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)
|
||||
}
|
||||
bot.createInlineFaucetHandler(ctx, q)
|
||||
}
|
||||
if strings.HasPrefix(q.Text, "tipjar") || strings.HasPrefix(q.Text, "spendendose") {
|
||||
if len(strings.Split(q.Text, " ")) > 1 {
|
||||
c := strings.Split(q.Text, " ")[0]
|
||||
ctx = bot.commandTranslationMap(ctx, c)
|
||||
}
|
||||
bot.handleInlineTipjarQuery(ctx, q)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(q.Text, "receive") || strings.HasPrefix(q.Text, "get") || strings.HasPrefix(q.Text, "payme") || strings.HasPrefix(q.Text, "request") {
|
||||
bot.handleInlineReceiveQuery(ctx, q)
|
||||
}
|
||||
}
|
||||
@@ -1,359 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"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 {
|
||||
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) {
|
||||
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
|
||||
}
|
||||
if amount < 1 {
|
||||
bot.inlineQueryReplyWithError(q, Translate(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQueryReceiveDescription"), bot.Telegram.Me.Username))
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
|
||||
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
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
if !inlineReceive.Active {
|
||||
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
|
||||
return
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
} 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
|
||||
}
|
||||
|
||||
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
|
||||
} else {
|
||||
// else, do an internal transaction
|
||||
bot.sendInlineReceiveHandler(ctx, c)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) sendInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
|
||||
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
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
|
||||
if !inlineReceive.Active {
|
||||
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
|
||||
return
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
log.Infof("[💸 inlineReceive] Send from %s to %s (%d sat).", fromUserStr, toUserStr, inlineReceive.Amount)
|
||||
inlineReceive.Set(inlineReceive, bot.Bunt)
|
||||
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) {
|
||||
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
|
||||
}
|
||||
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
|
||||
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, inlineReceive.Amount))
|
||||
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), inlineReceive.Amount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[acceptInlineReceiveHandler] Error: Receive message to %s: %s", toUserStr, err)
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
// inlineReceive.Release(inlineReceive, bot.Bunt)
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
|
||||
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
|
||||
}
|
||||
inlineReceive := rn.(*InlineReceive)
|
||||
if c.Sender.ID == inlineReceive.To.Telegram.ID {
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineReceive inactive
|
||||
inlineReceive.Active = false
|
||||
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -1,269 +0,0 @@
|
||||
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/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 (
|
||||
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 {
|
||||
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) {
|
||||
// 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
|
||||
}
|
||||
if amount < 1 {
|
||||
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(Translate(ctx, "inlineQuerySendDescription"), bot.Telegram.Me.Username))
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
to := LoadUser(ctx)
|
||||
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
if err != nil {
|
||||
// log.Errorf("[acceptInlineSendHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
inlineSend := sn.(*InlineSend)
|
||||
|
||||
fromUser := inlineSend.From
|
||||
if !inlineSend.Active {
|
||||
log.Errorf("[acceptInlineSendHandler] inline send not active anymore")
|
||||
return
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
} 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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
// 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
|
||||
}
|
||||
|
||||
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
|
||||
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
|
||||
_, err = bot.Telegram.Send(fromUser.Telegram, fmt.Sprintf(i18n.Translate(fromUser.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[sendInline] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
tx := &InlineSend{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelInlineSendHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
inlineSend := sn.(*InlineSend)
|
||||
if c.Sender.ID == inlineSend.From.Telegram.ID {
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineSend inactive
|
||||
inlineSend.Active = false
|
||||
runtime.IgnoreError(inlineSend.Set(inlineSend, bot.Bunt))
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -1,351 +0,0 @@
|
||||
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"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
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("inl-tipjar-%d-%d-%s", sender.ID, amount, RandStringRunes(5))
|
||||
|
||||
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) {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
if m.Private() {
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineTipjarHelpText"), Translate(ctx, "inlineTipjarHelpTipjarInGroup")))
|
||||
return
|
||||
}
|
||||
ctx = bot.mapTipjarLanguage(ctx, m.Text)
|
||||
inlineTipjar, err := bot.makeTipjar(ctx, m, false)
|
||||
if err != nil {
|
||||
log.Errorf("[tipjar] %s", err.Error())
|
||||
return
|
||||
}
|
||||
toUserStr := GetUserStr(m.Sender)
|
||||
bot.trySendMessage(m.Chat, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
|
||||
log.Infof("[tipjar] %s created tipjar %s: %d sat (%d per user)", toUserStr, inlineTipjar.ID, inlineTipjar.Amount, inlineTipjar.PerUserAmount)
|
||||
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
|
||||
}
|
||||
|
||||
func (bot TipBot) handleInlineTipjarQuery(ctx context.Context, q *tb.Query) {
|
||||
inlineTipjar, err := bot.makeQueryTipjar(ctx, q, false)
|
||||
if err != nil {
|
||||
// log.Errorf("[tipjar] %s", err.Error())
|
||||
return
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) acceptInlineTipjarHandler(ctx context.Context, c *tb.Callback) {
|
||||
from := LoadUser(ctx)
|
||||
if from.Wallet == nil {
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
inlineTipjar := fn.(*InlineTipjar)
|
||||
to := inlineTipjar.To
|
||||
if !inlineTipjar.Active {
|
||||
log.Errorf(fmt.Sprintf("[tipjar] tipjar %s inactive.", inlineTipjar.ID))
|
||||
return
|
||||
}
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
|
||||
return
|
||||
}
|
||||
// // 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
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineTipjarReceivedMessage"), fromUserStrMd, inlineTipjar.PerUserAmount))
|
||||
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineTipjarSentMessage"), inlineTipjar.PerUserAmount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[tipjar] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
// if inlineTipjar.UserNeedsWallet {
|
||||
// inlineTipjar.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
// }
|
||||
// update message
|
||||
log.Infoln(inlineTipjar.Message)
|
||||
bot.tryEditMessage(c.Message, inlineTipjar.Message, bot.makeTipjarKeyboard(ctx, inlineTipjar))
|
||||
}
|
||||
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,
|
||||
)
|
||||
// if inlineTipjar.UserNeedsWallet {
|
||||
// inlineTipjar.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
|
||||
// }
|
||||
bot.tryEditMessage(c.Message, inlineTipjar.Message)
|
||||
inlineTipjar.Active = false
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (bot *TipBot) cancelInlineTipjarHandler(ctx context.Context, c *tb.Callback) {
|
||||
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
|
||||
}
|
||||
inlineTipjar := fn.(*InlineTipjar)
|
||||
if c.Sender.ID == inlineTipjar.To.Telegram.ID {
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(inlineTipjar.LanguageCode, "inlineTipjarCancelledMessage"), &tb.ReplyMarkup{})
|
||||
// set the inlineTipjar inactive
|
||||
inlineTipjar.Active = false
|
||||
runtime.IgnoreError(inlineTipjar.Set(inlineTipjar, bot.Bunt))
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type CallbackFuncHandler func(ctx context.Context, message *tb.Callback)
|
||||
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)
|
||||
hm.handler(ctx, c)
|
||||
_, err = interceptCallback(ctx, c, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type MessageInterface interface {
|
||||
a() func(ctx context.Context, message *tb.Message)
|
||||
}
|
||||
type MessageFuncHandler func(ctx context.Context, message *tb.Message)
|
||||
|
||||
type 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)
|
||||
hm.handler(ctx, message)
|
||||
_, err = interceptMessage(ctx, message, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type QueryFuncHandler func(ctx context.Context, message *tb.Query)
|
||||
|
||||
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)
|
||||
hm.handler(ctx, query)
|
||||
_, err = interceptQuery(ctx, query, hm.after)
|
||||
if err != nil {
|
||||
log.Traceln(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
|
||||
"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
|
||||
)
|
||||
|
||||
var invalidTypeError = fmt.Errorf("invalid type")
|
||||
|
||||
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, invalidTypeError
|
||||
}
|
||||
|
||||
// unlockInterceptor invoked as onDefer interceptor
|
||||
func (bot TipBot) unlockInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
user := getTelegramUserFromInterface(i)
|
||||
if user != nil {
|
||||
mutex.Unlock(strconv.FormatInt(user.ID, 10))
|
||||
}
|
||||
return ctx, invalidTypeError
|
||||
}
|
||||
func (bot TipBot) idInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
return context.WithValue(ctx, "uid", RandStringRunes(64)), nil
|
||||
}
|
||||
|
||||
func (bot TipBot) answerCallbackInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
switch i.(type) {
|
||||
case *tb.Callback:
|
||||
c := i.(*tb.Callback)
|
||||
ctxcr := ctx.Value("callback_response")
|
||||
var res []*tb.CallbackResponse
|
||||
if ctxcr != nil {
|
||||
res = append(res, &tb.CallbackResponse{CallbackID: c.ID, Text: ctxcr.(string)})
|
||||
}
|
||||
var err error
|
||||
err = bot.Telegram.Respond(c, res...)
|
||||
return ctx, err
|
||||
}
|
||||
return ctx, invalidTypeError
|
||||
}
|
||||
|
||||
// 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, 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)
|
||||
if user != nil {
|
||||
return context.WithValue(ctx, "user", user), err
|
||||
}
|
||||
}
|
||||
return nil, invalidTypeError
|
||||
}
|
||||
|
||||
func (bot TipBot) loadUserInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
|
||||
ctx, _ = bot.requireUserInterceptor(ctx, i)
|
||||
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, 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, 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, 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
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
}
|
||||
userStr := GetUserStr(user.Telegram)
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
bot.tryDeleteMessage(m)
|
||||
return
|
||||
}
|
||||
// if no amount is in the command, ask for it
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
|
||||
// // no amount was entered, set user state and ask fo""r amount
|
||||
bot.askForAmount(ctx, "", "CreateInvoiceState", 0, 0, m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// 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.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
log.Infof("[/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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
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) {
|
||||
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"`
|
||||
}
|
||||
|
||||
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 {
|
||||
bot.trySendMessage(tx.User.Telegram, fmt.Sprintf(`✉️ %s`, str.MarkdownEscape(tx.Comment)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"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) {
|
||||
if internal.Configuration.Lnbits.LnbitsPublicUrl == "" {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "couldNotLinkMessage"))
|
||||
return
|
||||
}
|
||||
// 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 strings.HasPrefix(fromUser.Wallet.Adminkey, "banned") || strings.HasPrefix(fromUser.Wallet.Adminkey, "_") {
|
||||
return
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// 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))
|
||||
|
||||
}
|
||||
@@ -1,237 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"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) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
}
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("lnurlp-%d-%s", m.Sender.ID, RandStringRunes(5))
|
||||
lnurlPayState := &LnurlPayState{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
From: user,
|
||||
LNURLPayParams: payParams.LNURLPayParams,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
// 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 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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
|
||||
// directly go to confirm
|
||||
bot.lnurlPayHandlerSend(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
// lnurlPayHandlerSend is invoked when the user has delivered an amount and is ready to pay
|
||||
func (bot *TipBot) lnurlPayHandlerSend(ctx context.Context, m *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
}
|
||||
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
|
||||
|
||||
// assert that user has entered an amount
|
||||
if user.StateKey != lnbits.UserHasEnteredAmount {
|
||||
log.Errorln("[lnurlPayHandlerSend] state keys don't match")
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
// read the enter amount state from user.StateData
|
||||
var enterAmountData EnterAmountStateData
|
||||
err := json.Unmarshal([]byte(user.StateData), &enterAmountData)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
// use the enter amount state of the user to load the LNURL payment state
|
||||
tx := &LnurlPayState{Base: storage.New(storage.ID(enterAmountData.ID))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
fn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
body, err := ioutil.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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)
|
||||
bot.payHandler(ctx, m)
|
||||
}
|
||||
|
||||
func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, address string, amount int64) error {
|
||||
split := strings.Split(address, "@")
|
||||
if len(split) != 2 {
|
||||
return 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 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 nil
|
||||
}
|
||||
@@ -1,331 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
|
||||
"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"`
|
||||
}
|
||||
|
||||
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) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
}
|
||||
// object that holds all information about the send payment
|
||||
id := fmt.Sprintf("lnurlw-%d-%s", m.Sender.ID, RandStringRunes(5))
|
||||
LnurlWithdrawState := LnurlWithdrawState{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
From: user,
|
||||
LNURLWithdrawResponse: withdrawParams.LNURLWithdrawResponse,
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
|
||||
// directly go to confirm
|
||||
bot.lnurlWithdrawHandlerWithdraw(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
// lnurlWithdrawHandlerWithdraw is invoked when the user has delivered an amount and is ready to pay
|
||||
func (bot *TipBot) lnurlWithdrawHandlerWithdraw(ctx context.Context, m *tb.Message) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
}
|
||||
statusMsg := bot.trySendMessage(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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
var lnurlWithdrawState *LnurlWithdrawState
|
||||
switch fn.(type) {
|
||||
case *LnurlWithdrawState:
|
||||
lnurlWithdrawState = fn.(*LnurlWithdrawState)
|
||||
default:
|
||||
log.Errorf("[lnurlWithdrawHandlerWithdraw] invalid type")
|
||||
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
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")
|
||||
btnCancelWithdraw := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_withdraw")
|
||||
withdrawButton.Data = lnurlWithdrawState.ID
|
||||
btnCancelWithdraw.Data = 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))
|
||||
}
|
||||
|
||||
// confirmPayHandler when user clicked pay on payment confirmation
|
||||
func (bot *TipBot) confirmWithdrawHandler(ctx context.Context, c *tb.Callback) {
|
||||
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
|
||||
}
|
||||
|
||||
var lnurlWithdrawState *LnurlWithdrawState
|
||||
switch fn.(type) {
|
||||
case *LnurlWithdrawState:
|
||||
lnurlWithdrawState = fn.(*LnurlWithdrawState)
|
||||
default:
|
||||
log.Errorf("[confirmWithdrawHandler] invalid type")
|
||||
return
|
||||
}
|
||||
// onnly the correct user can press
|
||||
if lnurlWithdrawState.From.Telegram.ID != c.Sender.ID {
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
defer lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt)
|
||||
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// add response to persistent struct
|
||||
lnurlWithdrawState.LNURResponse = response2
|
||||
runtime.IgnoreError(lnurlWithdrawState.Set(lnurlWithdrawState, bot.Bunt))
|
||||
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot *TipBot) cancelWithdrawHandler(ctx context.Context, c *tb.Callback) {
|
||||
// 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
|
||||
}
|
||||
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
|
||||
}
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(lnurlWithdrawState.LanguageCode, "lnurlWithdrawCancelled"), &tb.ReplyMarkup{})
|
||||
lnurlWithdrawState.Inactivate(lnurlWithdrawState, bot.Bunt)
|
||||
}
|
||||
@@ -1,261 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"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) {
|
||||
// commands:
|
||||
// /lnurl
|
||||
// /lnurl <LNURL>
|
||||
// or /lnurl <amount> <LNURL>
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return
|
||||
}
|
||||
log.Infof("[lnurlHandler] %s", m.Text)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// if only /lnurl is entered, show the lnurl of the user
|
||||
if m.Text == "/lnurl" {
|
||||
bot.lnurlReceiveHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
statusMsg := bot.trySendMessage(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
|
||||
}
|
||||
|
||||
// get rid of the URI prefix
|
||||
lnurlSplit = strings.TrimPrefix(lnurlSplit, "lightning:")
|
||||
// HandleLNURL by fiatjaf/go-lnurl
|
||||
_, params, err := bot.HandleLNURL(lnurlSplit)
|
||||
if err != nil {
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
log.Warnf("[HandleLNURL] Error: %s", err.Error())
|
||||
return
|
||||
}
|
||||
switch params.(type) {
|
||||
case lnurl.LNURLPayParams:
|
||||
payParams := &LnurlPayState{LNURLPayParams: params.(lnurl.LNURLPayParams)}
|
||||
log.Infof("[LNURL-p] %s", payParams.LNURLPayParams.Callback)
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
bot.lnurlPayHandler(ctx, m, *payParams)
|
||||
return
|
||||
case lnurl.LNURLWithdrawResponse:
|
||||
withdrawParams := LnurlWithdrawState{LNURLWithdrawResponse: params.(lnurl.LNURLWithdrawResponse)}
|
||||
log.Infof("[LNURL-w] %s", withdrawParams.LNURLWithdrawResponse.Callback)
|
||||
bot.tryDeleteMessage(statusMsg)
|
||||
bot.lnurlWithdrawHandler(ctx, m, withdrawParams)
|
||||
default:
|
||||
if err == nil {
|
||||
err = errors.New("Invalid LNURL type.")
|
||||
}
|
||||
log.Warnln(err)
|
||||
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), err.Error()))
|
||||
// bot.trySendMessage(m.Sender, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
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.AnonID), strings.ToLower(internal.Configuration.Bot.LNURLHostUrl.Hostname())), nil
|
||||
}
|
||||
|
||||
func UserGetLNURL(user *lnbits.User) (string, error) {
|
||||
// before: we used the username for the LNURL
|
||||
// name := strings.ToLower(strings.ToLower(user.Telegram.Username))
|
||||
// if len(name) == 0 {
|
||||
// name = fmt.Sprint(user.AnonID)
|
||||
// // return "", fmt.Errorf("user has no username.")
|
||||
// }
|
||||
// now: use only the anon ID as LNURL
|
||||
name := fmt.Sprint(user.AnonID)
|
||||
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) {
|
||||
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.Telegram.Send(m.Sender, Translate(ctx, "lnurlNoUsernameMessage"))
|
||||
}
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(lnurlEncode, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[userLnurlHandler] Failed to create QR code for LNURL: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlReceiveInfoText"))
|
||||
// send the lnurl data to user
|
||||
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lnurlEncode)})
|
||||
}
|
||||
|
||||
// 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,
|
||||
errors.New("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, errors.New("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, errors.New("Unkown LNURL response.")
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
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)
|
||||
}()
|
||||
}
|
||||
@@ -1,251 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"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) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
}
|
||||
if len(strings.Split(m.Text, " ")) < 2 {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, ""))
|
||||
return
|
||||
}
|
||||
userStr := GetUserStr(m.Sender)
|
||||
paymentRequest, err := getArgumentFromCommand(m.Text, 1)
|
||||
if err != nil {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not getArgumentFromCommand: %s", err.Error())
|
||||
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.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
if amount > balance {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "insufficientFundsMessage"), balance, amount))
|
||||
return
|
||||
}
|
||||
// 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")
|
||||
cancelButton := paymentConfirmationMenu.Data(Translate(ctx, "cancelButtonMessage"), "cancel_pay")
|
||||
payButton.Data = id
|
||||
cancelButton.Data = id
|
||||
|
||||
paymentConfirmationMenu.Inline(
|
||||
paymentConfirmationMenu.Row(
|
||||
payButton,
|
||||
cancelButton),
|
||||
)
|
||||
payMessage := bot.trySendMessage(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)
|
||||
}
|
||||
|
||||
// confirmPayHandler when user clicked pay on payment confirmation
|
||||
func (bot *TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
|
||||
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
|
||||
}
|
||||
payData := sn.(*PayData)
|
||||
|
||||
// onnly the correct user can press
|
||||
if payData.From.Telegram.ID != c.Sender.ID {
|
||||
return
|
||||
}
|
||||
if !payData.Active {
|
||||
log.Errorf("[confirmPayHandler] send not active anymore")
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "errorTryLaterMessage"), &tb.ReplyMarkup{})
|
||||
bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
payData.Hash = invoice.PaymentHash
|
||||
|
||||
if c.Message.Private() {
|
||||
// if the command was invoked in private chat
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"), &tb.ReplyMarkup{})
|
||||
} else {
|
||||
// if the command was invoked in group chat
|
||||
bot.trySendMessage(c.Sender, i18n.Translate(payData.LanguageCode, "invoicePaidMessage"))
|
||||
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(payData.LanguageCode, "invoicePublicPaidMessage"), userStr), &tb.ReplyMarkup{})
|
||||
}
|
||||
log.Infof("[⚡️ pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
|
||||
return
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot *TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) {
|
||||
// reset state immediately
|
||||
user := LoadUser(ctx)
|
||||
ResetUserState(user, bot)
|
||||
tx := &PayData{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[cancelPaymentHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
payData := sn.(*PayData)
|
||||
// onnly the correct user can press
|
||||
if payData.From.Telegram.ID != c.Sender.ID {
|
||||
return
|
||||
}
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(payData.LanguageCode, "paymentCancelledMessage"), &tb.ReplyMarkup{})
|
||||
payData.Inactivate(payData, bot.Bunt)
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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/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) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return
|
||||
}
|
||||
if m.Photo == nil {
|
||||
return
|
||||
}
|
||||
user := LoadUser(ctx)
|
||||
if c := stateCallbackMessage[user.StateKey]; c != nil {
|
||||
c(ctx, m)
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
}
|
||||
|
||||
// get file reader closer from Telegram api
|
||||
reader, err := bot.Telegram.GetFile(m.Photo.MediaFile())
|
||||
if err != nil {
|
||||
log.Errorf("[photoHandler] getfile error: %v\n", err.Error())
|
||||
return
|
||||
}
|
||||
// decode to jpeg image
|
||||
img, err := jpeg.Decode(reader)
|
||||
if err != nil {
|
||||
log.Errorf("[photoHandler] image.Decode error: %v\n", err.Error())
|
||||
return
|
||||
}
|
||||
data, err := TryRecognizeQrCode(img)
|
||||
if err != nil {
|
||||
log.Errorf("[photoHandler] tryRecognizeQrCodes error: %v\n", err.Error())
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "photoQrNotRecognizedMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "photoQrRecognizedMessage"), data.String()))
|
||||
// invoke payment handler
|
||||
if lightning.IsInvoice(data.String()) {
|
||||
m.Text = fmt.Sprintf("/pay %s", data.String())
|
||||
bot.payHandler(ctx, m)
|
||||
return
|
||||
} else if lightning.IsLnurl(data.String()) {
|
||||
m.Text = fmt.Sprintf("/lnurl %s", data.String())
|
||||
bot.lnurlHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -1,322 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"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) {
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 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 {
|
||||
bot.tipHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
// if ok, errstr := bot.SendCheckSyntax(ctx, m); !ok {
|
||||
// bot.trySendMessage(m.Sender, helpSendUsage(ctx, errstr))
|
||||
// NewMessage(m, WithDuration(0, bot))
|
||||
// return
|
||||
// }
|
||||
|
||||
// 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
|
||||
err = bot.sendToLightningAddress(ctx, m, arg, amount)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// is a user given?
|
||||
arg, err = getArgumentFromCommand(m.Text, 1)
|
||||
if err != nil && m.Chat.Type == tb.ChatPrivate {
|
||||
bot.askForUser(ctx, "", "CreateSendState", m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// is an amount given?
|
||||
amount, err = decodeAmountFromCommand(m.Text)
|
||||
if (err != nil || amount < 1) && m.Chat.Type == tb.ChatPrivate {
|
||||
bot.askForAmount(ctx, "", "CreateSendState", 0, 0, m.Text)
|
||||
return
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
toUserStrWithoutAt = strings.TrimPrefix(toUserStrWithoutAt, "@")
|
||||
toUserStrMention = "@" + toUserStrWithoutAt
|
||||
}
|
||||
|
||||
err = bot.parseCmdDonHandler(ctx, m)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
toUserDb, err := GetUserByTelegramUsername(toUserStrWithoutAt, *bot)
|
||||
if err != nil {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
// cut username if it's too long
|
||||
if len(toUserStrMention) > 100 {
|
||||
toUserStrMention = toUserStrMention[:100]
|
||||
}
|
||||
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), str.MarkdownEscape(toUserStrMention)))
|
||||
return
|
||||
}
|
||||
|
||||
if user.ID == toUserDb.ID {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "sendYourselfMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// sendHandler invoked when user clicked send on payment confirmation
|
||||
func (bot *TipBot) confirmSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
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
|
||||
}
|
||||
sendData := sn.(*SendData)
|
||||
// onnly the correct user can press
|
||||
if sendData.From.Telegram.ID != c.Sender.ID {
|
||||
return
|
||||
}
|
||||
if !sendData.Active {
|
||||
log.Errorf("[acceptSendHandler] send not active anymore")
|
||||
// bot.tryDeleteMessage(c.Message)
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
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
|
||||
bot.tryEditMessage(c.Message, fmt.Sprintf(i18n.Translate(sendData.LanguageCode, "sendSentMessage"), amount, toUserStrMd), &tb.ReplyMarkup{})
|
||||
} else {
|
||||
// if the command was invoked in group chat
|
||||
bot.trySendMessage(c.Sender, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "sendSentMessage"), amount, toUserStrMd))
|
||||
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
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot *TipBot) cancelSendHandler(ctx context.Context, c *tb.Callback) {
|
||||
// reset state immediately
|
||||
user := LoadUser(ctx)
|
||||
ResetUserState(user, bot)
|
||||
tx := &SendData{Base: storage.New(storage.ID(c.Data))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.Bunt)
|
||||
if err != nil {
|
||||
log.Errorf("[acceptSendHandler] %s", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
sendData := sn.(*SendData)
|
||||
// onnly the correct user can press
|
||||
if sendData.From.Telegram.ID != c.Sender.ID {
|
||||
return
|
||||
}
|
||||
// remove buttons from confirmation message
|
||||
bot.tryEditMessage(c.Message, i18n.Translate(sendData.LanguageCode, "sendCancelledMessage"), &tb.ReplyMarkup{})
|
||||
sendData.Inactivate(sendData, bot.Bunt)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,296 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot TipBot) shopsMainMenu(ctx context.Context, shops *Shops) *tb.ReplyMarkup {
|
||||
browseShopButton := shopKeyboard.Data("🛍 Browse shops", "shops_browse", shops.ID)
|
||||
shopNewShopButton := shopKeyboard.Data("✅ New Shop", "shops_newshop", shops.ID)
|
||||
shopSettingsButton := shopKeyboard.Data("⚙️ Settings", "shops_settings", shops.ID)
|
||||
user := LoadUser(ctx)
|
||||
|
||||
buttons := []tb.Row{}
|
||||
if len(shops.Shops) > 0 {
|
||||
buttons = append(buttons, shopKeyboard.Row(browseShopButton))
|
||||
}
|
||||
if user.Telegram.ID == shops.Owner.Telegram.ID {
|
||||
buttons = append(buttons, shopKeyboard.Row(shopNewShopButton, shopSettingsButton))
|
||||
}
|
||||
shopKeyboard.Inline(
|
||||
buttons...,
|
||||
)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
func (bot TipBot) shopsSettingsMenu(ctx context.Context, shops *Shops) *tb.ReplyMarkup {
|
||||
shopShopsButton := shopKeyboard.Data("⬅️ Back", "shops_shops", shops.ID)
|
||||
shopLinkShopButton := shopKeyboard.Data("🔗 Shop links", "shops_linkshop", shops.ID)
|
||||
shopRenameShopButton := shopKeyboard.Data("⌨️ Rename a shop", "shops_renameshop", shops.ID)
|
||||
shopDeleteShopButton := shopKeyboard.Data("🚫 Delete shops", "shops_deleteshop", shops.ID)
|
||||
shopDescriptionShopButton := shopKeyboard.Data("💬 Description", "shops_description", shops.ID)
|
||||
// // shopResetShopButton := shopKeyboard.Data("⚠️ Delete all shops", "shops_reset", shops.ID)
|
||||
// buttons := []tb.Row{
|
||||
// shopKeyboard.Row(shopLinkShopButton),
|
||||
// shopKeyboard.Row(shopDescriptionShopButton),
|
||||
// shopKeyboard.Row(shopRenameShopButton),
|
||||
// shopKeyboard.Row(shopDeleteShopButton),
|
||||
// // shopKeyboard.Row(shopResetShopButton),
|
||||
// shopKeyboard.Row(shopShopsButton),
|
||||
// }
|
||||
// shopKeyboard.Inline(
|
||||
// buttons...,
|
||||
// )
|
||||
|
||||
button := []tb.Btn{
|
||||
shopLinkShopButton,
|
||||
shopDescriptionShopButton,
|
||||
shopRenameShopButton,
|
||||
shopDeleteShopButton,
|
||||
shopShopsButton,
|
||||
}
|
||||
shopKeyboard.Inline(buttonWrapper(button, shopKeyboard, 2)...)
|
||||
return shopKeyboard
|
||||
}
|
||||
|
||||
// shopItemSettingsMenu builds the buttons of the item settings
|
||||
func (bot TipBot) shopItemSettingsMenu(ctx context.Context, shop *Shop, item *ShopItem) *tb.ReplyMarkup {
|
||||
shopItemPriceButton = shopKeyboard.Data("💯 Set price", "shop_itemprice", item.ID)
|
||||
shopItemDeleteButton = shopKeyboard.Data("🚫 Delete item", "shop_itemdelete", item.ID)
|
||||
shopItemTitleButton = shopKeyboard.Data("⌨️ Set title", "shop_itemtitle", item.ID)
|
||||
shopItemAddFileButton = shopKeyboard.Data("💾 Add file", "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, start int) (shopView ShopView, err error) {
|
||||
mutex.Lock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
|
||||
shopView, err = bot.getUserShopview(ctx, user)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
statusMessages := shopView.StatusMessages
|
||||
// delete all status messages from cache
|
||||
shopView.StatusMessages = append([]*tb.Message{}, statusMessages[0:start]...)
|
||||
bot.Cache.Set(shopView.ID, shopView, &store.Options{Expiration: 24 * time.Hour})
|
||||
|
||||
deleteStatusMessages(start, statusMessages, bot)
|
||||
mutex.Unlock(fmt.Sprintf("shopview-delete-%d", user.Telegram.ID))
|
||||
return
|
||||
}
|
||||
|
||||
func deleteStatusMessages(start int, messages []*tb.Message, bot *TipBot) {
|
||||
// delete all status messages from telegram
|
||||
for _, msg := range messages[start:] {
|
||||
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)
|
||||
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})
|
||||
mutex.Unlock(id)
|
||||
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, 1)
|
||||
// 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)),
|
||||
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)))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
sn, err := tx.Get(tx, bot.ShopBunt)
|
||||
if err != nil {
|
||||
log.Errorf("[getUserShops] User: %s (%d): %s", GetUserStr(user.Telegram), user.Telegram.ID, err)
|
||||
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)),
|
||||
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 for the given ID
|
||||
func (bot *TipBot) getShop(ctx context.Context, shopId string) (*Shop, error) {
|
||||
tx := &Shop{Base: storage.New(storage.ID(shopId))}
|
||||
mutex.LockWithContext(ctx, tx.ID)
|
||||
defer mutex.UnlockWithContext(ctx, tx.ID)
|
||||
// immediatelly set intransaction to block duplicate calls
|
||||
sn, err := tx.Get(tx, bot.ShopBunt)
|
||||
if err != nil {
|
||||
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
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
)
|
||||
|
||||
type StateCallbackMessage map[lnbits.UserStateKey]func(ctx context.Context, m *tb.Message)
|
||||
|
||||
var stateCallbackMessage StateCallbackMessage
|
||||
|
||||
func initializeStateCallbackMessage(bot *TipBot) {
|
||||
stateCallbackMessage = StateCallbackMessage{
|
||||
lnbits.UserStateLNURLEnterAmount: bot.enterAmountHandler,
|
||||
lnbits.UserEnterAmount: bot.enterAmountHandler,
|
||||
lnbits.UserEnterUser: bot.enterUserHandler,
|
||||
lnbits.UserEnterShopTitle: bot.enterShopTitleHandler,
|
||||
lnbits.UserStateShopItemSendPhoto: bot.addShopItemPhoto,
|
||||
lnbits.UserStateShopItemSendPrice: bot.enterShopItemPriceHandler,
|
||||
lnbits.UserStateShopItemSendTitle: bot.enterShopItemTitleHandler,
|
||||
lnbits.UserStateShopItemSendItemFile: bot.addItemFileHandler,
|
||||
lnbits.UserEnterShopsDescription: bot.enterShopsDescriptionHandler,
|
||||
}
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
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"
|
||||
)
|
||||
|
||||
// appendMainMenu will check if to (recipient) ID is from private or group chat.
|
||||
// this function will only add a keyboard if this is a private chat and no force reply.
|
||||
func appendMainMenu(to int64, options []interface{}) []interface{} {
|
||||
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
|
||||
}
|
||||
|
||||
// getChatIdFromRecipient will parse the recipient to int64
|
||||
func 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 := getChatIdFromRecipient(to)
|
||||
if err != nil {
|
||||
log.Errorf("[tryForwardMessage] error converting message recipient to int64: %v", err)
|
||||
return
|
||||
}
|
||||
msg, err = bot.Telegram.Forward(to, what, appendMainMenu(chatId, 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 := getChatIdFromRecipient(to)
|
||||
if err != nil {
|
||||
log.Errorf("[trySendMessage] error converting message recipient to int64: %v", err)
|
||||
return
|
||||
}
|
||||
msg, err = bot.Telegram.Send(to, what, appendMainMenu(chatId, 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, appendMainMenu(to.Chat.ID, options)...)
|
||||
if err != nil {
|
||||
log.Warnln(err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...interface{}) (msg *tb.Message) {
|
||||
rate.CheckLimit(to)
|
||||
var err error
|
||||
_, chatId := to.MessageSig()
|
||||
msg, err = bot.Telegram.Edit(to, what, appendMainMenu(chatId, 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
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"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) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return
|
||||
}
|
||||
|
||||
// check if user is in Database, if not, initialize wallet
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil || !user.Initialized {
|
||||
bot.startHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
|
||||
// could be an invoice
|
||||
anyText := strings.ToLower(m.Text)
|
||||
if lightning.IsInvoice(anyText) {
|
||||
m.Text = "/pay " + anyText
|
||||
bot.payHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
if lightning.IsLnurl(anyText) {
|
||||
m.Text = "/lnurl " + anyText
|
||||
bot.lnurlHandler(ctx, m)
|
||||
return
|
||||
}
|
||||
if c := stateCallbackMessage[user.StateKey]; c != nil {
|
||||
c(ctx, m)
|
||||
//ResetUserState(user, bot)
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return // errors.New("user has no wallet"), 0
|
||||
}
|
||||
|
||||
if !(user.StateKey == lnbits.UserEnterUser) {
|
||||
ResetUserState(user, bot)
|
||||
return // errors.New("user state does not match"), 0
|
||||
}
|
||||
if len(m.Text) < 4 || strings.HasPrefix(m.Text, "/") {
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
}
|
||||
|
||||
var EnterUserStateData EnterUserStateData
|
||||
err := json.Unmarshal([]byte(user.StateData), &EnterUserStateData)
|
||||
if err != nil {
|
||||
log.Errorf("[EnterUserHandler] %s", err.Error())
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
}
|
||||
|
||||
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)
|
||||
bot.sendHandler(ctx, m)
|
||||
return
|
||||
default:
|
||||
ResetUserState(user, bot)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"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) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(ctx, m)
|
||||
user := LoadUser(ctx)
|
||||
if user.Wallet == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
if ok, err := TipCheckSyntax(ctx, m); !ok {
|
||||
bot.trySendMessage(m.Sender, helpTipUsage(ctx, err))
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
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, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, helpTipUsage(ctx, Translate(ctx, "tipValidAmountMessage")))
|
||||
log.Warnln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
err = bot.parseCmdDonHandler(ctx, m)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
// TIP COMMAND IS VALID
|
||||
from := LoadUser(ctx)
|
||||
to := LoadReplyToUser(ctx)
|
||||
|
||||
if from.Telegram.ID == to.Telegram.ID {
|
||||
NewMessage(m, WithDuration(0, bot))
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "tipYourselfMessage"))
|
||||
return
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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
|
||||
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "tipSentMessage"), amount, toUserStrMd))
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[/tip] Error: Send message to %s: %s", toUserStr, err)
|
||||
log.Warnln(errmsg)
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
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,132 +0,0 @@
|
||||
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
|
||||
}
|
||||
return true, err
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
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
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
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,20 +1,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits/webhook"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/price"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
log "github.com/sirupsen/logrus"
|
||||
_ "net/http/pprof"
|
||||
)
|
||||
|
||||
// setLogger will initialize the log format
|
||||
func setLogger() {
|
||||
log.SetLevel(log.TraceLevel)
|
||||
log.SetLevel(log.InfoLevel)
|
||||
customFormatter := new(log.TextFormatter)
|
||||
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
|
||||
customFormatter.FullTimestamp = true
|
||||
@@ -24,18 +16,13 @@ func setLogger() {
|
||||
func main() {
|
||||
// set logger
|
||||
setLogger()
|
||||
go http.ListenAndServe("0.0.0.0:6060", nil)
|
||||
defer withRecovery()
|
||||
bot := telegram.NewBot()
|
||||
webhook.NewServer(&bot)
|
||||
lnurl.NewServer(&bot)
|
||||
price.NewPriceWatcher().Start()
|
||||
bot := NewBot()
|
||||
bot.Start()
|
||||
}
|
||||
|
||||
func withRecovery() {
|
||||
if r := recover(); r != nil {
|
||||
log.Errorln("Recovered panic: ", r)
|
||||
debug.PrintStack()
|
||||
}
|
||||
}
|
||||
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
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:]...)
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
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
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
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,36 +1,18 @@
|
||||
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(message string) bool {
|
||||
message = strings.ToLower(message)
|
||||
func IsInvoice(invoice string) bool {
|
||||
// invoice string must start with lnbc or lightning:lnbc
|
||||
if strings.HasPrefix(message, "lnbc") || strings.HasPrefix(message, "lightning:lnbc") {
|
||||
if strings.HasPrefix(invoice, "lnbc") || strings.HasPrefix(invoice, "lightning:lnbc") {
|
||||
// invoice string must be a single word
|
||||
if !strings.Contains(message, " ") {
|
||||
if !strings.Contains(invoice, " ") {
|
||||
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.
|
Before Width: | Height: | Size: 26 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 107 KiB After Width: | Height: | Size: 172 KiB |
@@ -0,0 +1,278 @@
|
||||
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,63 +1,63 @@
|
||||
package telegram
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func (bot TipBot) startHandler(ctx context.Context, m *tb.Message) {
|
||||
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)
|
||||
log.Printf("[⭐️ /start] New user: %s (%d)\n", GetUserStr(m.Sender), m.Sender.ID)
|
||||
walletCreationMsg, err := bot.Telegram.Send(m.Sender, Translate(ctx, "startSettingWalletMessage"))
|
||||
user, err := bot.initWallet(m.Sender)
|
||||
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.tryEditMessage(walletCreationMsg, Translate(ctx, "startWalletErrorMessage"))
|
||||
bot.telegram.Edit(walletCreationMsg, startWalletErrorMessage)
|
||||
return
|
||||
}
|
||||
bot.tryDeleteMessage(walletCreationMsg)
|
||||
ctx = context.WithValue(ctx, "user", user)
|
||||
bot.helpHandler(ctx, m)
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "startWalletReadyMessage"))
|
||||
bot.balanceHandler(ctx, m)
|
||||
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.trySendMessage(m.Sender, Translate(ctx, "startNoUsernameMessage"), tb.NoPreview)
|
||||
bot.telegram.Send(m.Sender, startNoUsernameMessage, tb.NoPreview)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
|
||||
func (bot TipBot) initWallet(tguser *tb.User) error {
|
||||
user, err := GetUser(tguser, bot)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
user = &lnbits.User{Telegram: tguser}
|
||||
err = bot.createWallet(user)
|
||||
u := &lnbits.User{Telegram: tguser}
|
||||
err = bot.createWallet(u)
|
||||
if err != nil {
|
||||
return user, err
|
||||
return err
|
||||
}
|
||||
user.Initialized = true
|
||||
err = UpdateUserRecord(user, bot)
|
||||
u.Initialized = true
|
||||
err = UpdateUserRecord(u, bot)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
|
||||
return user, err
|
||||
return err
|
||||
}
|
||||
} else if !user.Initialized {
|
||||
// update all tip tooltips (with the "initialize me" message) that this user might have received before
|
||||
@@ -66,45 +66,44 @@ func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
|
||||
return user, err
|
||||
return err
|
||||
}
|
||||
} else if user.Initialized {
|
||||
// wallet is already initialized
|
||||
return user, nil
|
||||
return nil
|
||||
} else {
|
||||
err = fmt.Errorf("could not initialize wallet")
|
||||
return user, err
|
||||
return err
|
||||
}
|
||||
return user, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func (bot TipBot) createWallet(user *lnbits.User) error {
|
||||
UserStr := GetUserStr(user.Telegram)
|
||||
u, err := bot.Client.CreateUserWithInitialWallet(strconv.FormatInt(user.Telegram.ID, 10),
|
||||
u, err := bot.client.CreateUserWithInitialWallet(strconv.Itoa(user.Telegram.ID),
|
||||
fmt.Sprintf("%d (%s)", user.Telegram.ID, UserStr),
|
||||
internal.Configuration.Lnbits.AdminId,
|
||||
Configuration.AdminKey,
|
||||
UserStr)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err.Error())
|
||||
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err)
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
user.Wallet = &lnbits.Wallet{}
|
||||
user.Wallet = &lnbits.Wallet{Client: bot.client}
|
||||
user.ID = u.ID
|
||||
user.Name = u.Name
|
||||
wallet, err := bot.Client.Wallets(*user)
|
||||
wallet, err := user.Wallet.Wallets(*user)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err.Error())
|
||||
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err)
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
user.Wallet = &wallet[0]
|
||||
user.AnonID = fmt.Sprint(str.Int32Hash(user.ID))
|
||||
user.Wallet.Client = bot.client
|
||||
user.Initialized = false
|
||||
user.CreatedAt = time.Now()
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err.Error())
|
||||
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err)
|
||||
log.Errorln(errormsg)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
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
@@ -0,0 +1,149 @@
|
||||
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
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
package telegram
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -44,8 +44,8 @@ func Test_getTippersString(t *testing.T) {
|
||||
|
||||
func TestMessage_getTooltipMessage(t *testing.T) {
|
||||
type fields struct {
|
||||
Message Message
|
||||
TipAmount int64
|
||||
Message *tb.Message
|
||||
TipAmount int
|
||||
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: Message{}, TipAmount: 10, Ntips: 1, Tippers: append(tippers, tipper1)},
|
||||
fields: fields{Message: &tb.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: Message{}, TipAmount: 100, Ntips: 6, Tippers: append(tippers, tipper1, tipper2, tipper3, tipper4, tipper5, tipper6)},
|
||||
fields: fields{Message: &tb.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 := TipTooltip{
|
||||
x := Message{
|
||||
Message: tt.fields.Message,
|
||||
TipAmount: tt.fields.TipAmount,
|
||||
Ntips: tt.fields.Ntips,
|
||||
LastTip: tt.fields.LastTip,
|
||||
Tippers: tt.fields.Tippers,
|
||||
}
|
||||
if got := x.getUpdatedTipTooltipMessage(tt.args.botUserName, tt.args.notInitializedWallet); got != tt.want {
|
||||
t.Errorf("getUpdatedTipTooltipMessage() = %v, want %v", got, tt.want)
|
||||
if got := x.getTooltipMessage(tt.args.botUserName, tt.args.notInitializedWallet); got != tt.want {
|
||||
t.Errorf("getTooltipMessage() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
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
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
# 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 :)
|
||||
@@ -1,336 +0,0 @@
|
||||
# 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 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 diesem 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`"""
|
||||
@@ -1,341 +0,0 @@
|
||||
# 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 Lightning address."""
|
||||
invoiceNoAmountMessage = """🚫 Can't pay invoices without an amount."""
|
||||
insufficientFundsMessage = """🚫 Insufficient funds. You have %d sat but you need at least %d sat."""
|
||||
feeReserveMessage = """⚠️ Sending your entire balance might fail because of network fees. If it fails, try sending a bit less."""
|
||||
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 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 this 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."""
|
||||
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)."""
|
||||
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`"""
|
||||
@@ -1,336 +0,0 @@
|
||||
# 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 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.
|
||||
|
||||
🚰 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`"""
|
||||
@@ -1,304 +0,0 @@
|
||||
# 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.
|
||||
|
||||
🚰 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."""
|
||||
@@ -1,312 +0,0 @@
|
||||
# COMMANDS
|
||||
|
||||
helpCommandStr = """bantuan"""
|
||||
basicsCommandStr = """dasar"""
|
||||
tipCommandStr = """tip"""
|
||||
balanceCommandStr = """saldo"""
|
||||
sendCommandStr = """kirim"""
|
||||
invoiceCommandStr = """invoice"""
|
||||
payCommandStr = """bayar"""
|
||||
donateCommandStr = """donasi"""
|
||||
advancedCommandStr = """lanjutan"""
|
||||
transactionsCommandStr = """transaksi"""
|
||||
logCommandStr = """log"""
|
||||
listCommandStr = """daftar"""
|
||||
|
||||
linkCommandStr = """link"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """keran"""
|
||||
|
||||
tipjarCommandStr = """tipjar"""
|
||||
receiveCommandStr = """terima"""
|
||||
hideCommandStr = """sembunyikan"""
|
||||
volcanoCommandStr = """volcano"""
|
||||
showCommandStr = """munculkan"""
|
||||
optionsCommandStr = """pilihan"""
|
||||
settingsCommandStr = """pengaturan"""
|
||||
saveCommandStr = """simpan"""
|
||||
deleteCommandStr = """hapus"""
|
||||
infoCommandStr = """info"""
|
||||
|
||||
# NOTIFICATIONS
|
||||
|
||||
cantDoThatMessage = """Kamu tidak bisa melakukan itu."""
|
||||
cantClickMessage = """Kamu tidak dapat menekan tombol itu."""
|
||||
balanceTooLowMessage = """Saldo mu terlalu rendah."""
|
||||
|
||||
# BUTTONS
|
||||
|
||||
sendButtonMessage = """✅ Kirim"""
|
||||
payButtonMessage = """✅ Bayar"""
|
||||
payReceiveButtonMessage = """💸 Bayar"""
|
||||
receiveButtonMessage = """✅ Terima"""
|
||||
cancelButtonMessage = """🚫 Batal"""
|
||||
collectButtonMessage = """✅ Ambil"""
|
||||
nextButtonMessage = """Lanjut"""
|
||||
backButtonMessage = """Kembali"""
|
||||
acceptButtonMessage = """Setuju"""
|
||||
denyButtonMessage = """Tolak"""
|
||||
tipButtonMessage = """Tip"""
|
||||
revealButtonMessage = """Perlihatkan"""
|
||||
showButtonMessage = """Munculkan"""
|
||||
hideButtonMessage = """Sembunyikan"""
|
||||
joinButtonMessage = """Bergabung"""
|
||||
optionsButtonMessage = """Pilihan"""
|
||||
settingsButtonMessage = """Pengaturan"""
|
||||
saveButtonMessage = """Simpan"""
|
||||
deleteButtonMessage = """Hapus"""
|
||||
infoButtonMessage = """Info"""
|
||||
|
||||
# HELP
|
||||
|
||||
helpMessage = """⚡️ *Dompet*
|
||||
_Bot ini adalah sebuah dompet Bitcoin Lightning yang dapat mengirimkan tip melalui Telegram. Untuk memberi tip, tambahkan bot ke chat grup. Unit dasar dari tip adalah Satoshi (sat). 100,000,000 sat = 1 Bitcoin. Ketik 📚 /basics untuk informasi lebih banyak._
|
||||
|
||||
❤️ *Donasi*
|
||||
_Bot ini tidak memungut biaya tapi memerlukan Satoshi untuk bekerja. Kalau kamu menyukai bot ini, tolong pertimbangkan mendukung proyek ini dengan donasi. Untuk melakukan donasi, pakai_ `/donate 1000`
|
||||
|
||||
%s
|
||||
|
||||
⚙️ *Commands*
|
||||
*/tip* 🏅 Membalas sebuah pesan untuk memberi tip: `/tip <jumlah> [<berita>]`
|
||||
*/balance* 👑 Memeriksa saldo mu: `/balance`
|
||||
*/send* 💸 Mengirim dana ke seorang pengguna: `/send <jumlah> @user or user@ln.tips [<berita>]`
|
||||
*/invoice* ⚡️ Menerima menggunakan Lightning: `/invoice <jumlah> [<berita>]`
|
||||
*/pay* ⚡️ Membayar dengan Lightning: `/pay <invoice>`
|
||||
*/donate* ❤️ Memberi donasi ke proyek: `/donate 1000`
|
||||
*/advanced* 🤖 Fitur lanjutan.
|
||||
*/help* 📖 Membaca daftar bantuan."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Info*"""
|
||||
infoYourLightningAddress = """Alamat Lightning mu adalah `%s`"""
|
||||
|
||||
basicsMessage = """🧡 *Bitcoin*
|
||||
_Bitcoin adalah mata uang dari internet. Tidak memerlukan ijin dan terdesentralisasi dan tidak memiliki penguasa dan tidak ada otoritas yang mengatur. Bitcoin adalah uang yang tangguh yang lebih cepat, lebih aman, dan lebih inklusif dibanding sistem keuangan tradisional._
|
||||
|
||||
🧮 *Ekonomi*
|
||||
_Unit terkecil dari Bitcoin adalah Satoshi (sat) dan 100,000,000 sat = 1 Bitcoin. Hanya akan pernah ada 21 Juta Bitcoin. Nilai Bitcoin dalam mata uang fiat dapat berubah tiap hari. Namun, jika kamu hidup dalam sebuah standar Bitcoin maka 1 sat akan selalu sama dengan 1 sat._
|
||||
|
||||
⚡️ *The Lightning Network*
|
||||
_Lightning Network adalah sebuah protokol pembayaran yang memungkinkan pembayaran Bitcoin dengan cepat dan murah yang memerlukan hampir tidak ada energi. Ini lah yang membesarkan skala Bitcoin ke milyaran orang diseluruh dunia._
|
||||
|
||||
📲 *Lightning Wallets*
|
||||
_Dana mu di bot ini dapat dikirim ke dompet Lightning manapun lainnya dan kebalikannya. Rekomendasi dompet Lightning untuk handphone mu adalah_ [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*
|
||||
_Bot ini gratis dan merupakan perangkat lunak_ [open source](https://github.com/LightningTipBot/LightningTipBot) _. Kamu dapat menjalankannya di komputer mu sendiri dan menggunakannya di komunitas mu._
|
||||
|
||||
✈️ *Telegram*
|
||||
_Tambahkan bot ini ke percakapan grup Telegram mu untuk /tip postingan. Jika kamu membuat bot ini sebagai admin maka akan membersihkan perintah untuk agar percakapan tetap rapi._
|
||||
|
||||
🏛 *Persyaratan*
|
||||
_Kami tidak menyimpan dana mu. Kami akan bertindak yang terbaik untuk kamu namun kami juga sadar bahwa situasi tanpa KYC agak sulit sampai kami bisa memikirkan sesuatu. Berapa pun jumlah yang kamu masukkan ke dompet mu akan dianggap sebagai donasi. Jangan kirim ke kami semua uang mu. Tolong sadar bahwa bot ini masih dalam perkembangan beta. Pergunakan lah dengan resiko mu sendiri._
|
||||
|
||||
❤️ *Donasi*
|
||||
_Bot ini tidak memungut biaya tapi memerlukan Satoshi untuk bekerja. Kalau kamu menyukai bot ini, tolong pertimbangkan mendukung proyek ini dengan donasi. Untuk melakukan donasi, pakai_ `/donate 1000`"""
|
||||
|
||||
helpNoUsernameMessage = """👋 Silakan mengatur nama pengguna untuk Telegram."""
|
||||
|
||||
advancedMessage = """%s
|
||||
|
||||
👉 *Sebaris perintah*
|
||||
*send* 💸 Kirim sats ke percakapan: `%s send <jumlah> [<berita>]`
|
||||
*receive* 🏅 Permintaan pembayaran: `... receive <jumlah> [<berita>]`
|
||||
*faucet* 🚰 Membuat sebuah keran: `... faucet <kapasitas> <per_pengguna>`
|
||||
*tipjar* 🍯 Create a tipjar: `... tipjar <capacity> <per_user> [<memo>]`
|
||||
|
||||
📖 Kamu dapat menggunakan sebaris perintah di tiap percakapan, bahkan di percakapan privat. Tunggu sejenak setelah memasukkan sebaris perintah lalu *pencet* hasilnya, jangan tekan enter.
|
||||
|
||||
⚙️ *Perintah lanjutan*
|
||||
*/link* 🔗 Menghubungkan dompet mu ke [BlueWallet](https://bluewallet.io/) atau [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl menerima atau membayar: `/lnurl` atau `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Membuat sebuah keran `/faucet <kapasitas> <per_pengguna>`
|
||||
*/tipjar* 🍯 Create a tipjar: `/tipjar <capacity> <per_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Masukkan jumlah diantara %d dan %d sat."""
|
||||
enterAmountMessage = """💯 Masukkan jumlah."""
|
||||
enterUserMessage = """👤 Masukkan user."""
|
||||
errorReasonMessage = """🚫 Error: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Sedang menyiapkan dompet mu..."""
|
||||
startWalletCreatedMessage = """🧮 Dompet sudah dibuat."""
|
||||
startWalletReadyMessage = """✅ *Dompet mu sudah siap.*"""
|
||||
startWalletErrorMessage = """🚫 Ada kesalahan dalam pembuatan dompet mu. Silakan coba lagi nanti."""
|
||||
startNoUsernameMessage = """☝️ Kelihatannya kamu belum memiliki sebuah @username Telegram. Tidak apa-apa, kamu tidak memerlukan nya untuk menggunakan bot ini. Namun, agar dompet mu bisa lebih berguna, atur nama pengguna di pengaturan Telegram. Lalu, ketik /balance agar bot dapat memperbaharui catatan nya mengenai kamu."""
|
||||
|
||||
# BALANCE
|
||||
|
||||
balanceMessage = """👑 *Saldo mu:* %d sat"""
|
||||
balanceErrorMessage = """🚫 Tidak dapat memeriksa saldo mu. Tolong coba lagi nanti."""
|
||||
|
||||
# TIP
|
||||
|
||||
tipDidYouReplyMessage = """Apakah kamu tadi membalas pesan untuk memberikan tip? Untuk membalas pesan mana pun, klik-kanan -> Ketik balasan pada komputer mu atau geser pesan yang ada di handphone mu. Jika kamu mau mengirimkan secara langsung, gunakan perintah /send ."""
|
||||
tipInviteGroupMessage = """ℹ️ Ngomong-ngomong, kamu bisa mengundang bot ini ke grup mana saja untuk mulai memberikan tip disana."""
|
||||
tipEnterAmountMessage = """Apakah kamu sudah memasukkan jumlah?"""
|
||||
tipValidAmountMessage = """Apakah kamu memasukkan jumlah yang benar?"""
|
||||
tipYourselfMessage = """📖 Kamu tidak dapat memberi tip ke diri sendiri."""
|
||||
tipSentMessage = """💸 %d sat terkirim ke %s."""
|
||||
tipReceivedMessage = """🏅 %s telah memberi tip sebanyak %d sat."""
|
||||
tipErrorMessage = """🚫 Pengiriman tip gagal."""
|
||||
tipUndefinedErrorMsg = """Silakan coba lagi nanti."""
|
||||
tipHelpText = """📖 Waduh, itu tidak berhasil. %s
|
||||
|
||||
*Usage:* `/tip <jumlah> [<berita>]`
|
||||
*Example:* `/tip 1000 Makasih!`"""
|
||||
|
||||
# SEND
|
||||
|
||||
sendValidAmountMessage = """Apakah kamu memasukkan jumlah yang benar?"""
|
||||
sendUserHasNoWalletMessage = """🚫 Pengguna %s belum membuat dompet."""
|
||||
sendSentMessage = """💸 %d sat terkirim ke %s."""
|
||||
sendPublicSentMessage = """💸 %d sat terkirim dari %s ke %s."""
|
||||
sendReceivedMessage = """🏅 %s mengirimkan kamu %d sat."""
|
||||
sendErrorMessage = """🚫 Pengiriman gagal."""
|
||||
confirmSendMessage = """Apakah kamu ingin membayar ke %s?\n\n💸 Jumlah: %d sat"""
|
||||
confirmSendAppendMemo = """\n✉️ %s"""
|
||||
sendCancelledMessage = """🚫 Pengiriman dibatalkan."""
|
||||
errorTryLaterMessage = """🚫 Error. Silakan coba lagi nanti."""
|
||||
sendSyntaxErrorMessage = """Apakah kamu sudah memasukkan jumlah dan penerima? Kamu dapat menggunakan perintah /send untuk ke pengguna Telegram seperti %s atau ke alamat Lightning seperti LightningTipBot@ln.tips."""
|
||||
sendHelpText = """📖 Waduh, itu tidak berhasil. %s
|
||||
|
||||
*Usage:* `/send <jumlah> <pengguna> [<berita>]`
|
||||
*Example:* `/send 1000 @LightningTipBot Gampang botnya dipakai ❤️`
|
||||
*Example:* `/send 1234 LightningTipBot@ln.tips`"""
|
||||
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Kamu menerima %d sat."""
|
||||
invoiceEnterAmountMessage = """Apakah kamu sudah memasukkan jumlah?"""
|
||||
invoiceValidAmountMessage = """Apakah kamu memasukkan jumlah yang benar?"""
|
||||
invoiceHelpText = """📖 Waduh, itu tidak berhasil. %s
|
||||
|
||||
*Usage:* `/invoice <jumlah> [<berita>]`
|
||||
*Example:* `/invoice 1000 Makasih!`"""
|
||||
|
||||
# PAY
|
||||
|
||||
paymentCancelledMessage = """🚫 Pembayaran dibatalkan."""
|
||||
invoicePaidMessage = """⚡️ Pembayaran terkirim."""
|
||||
invoicePublicPaidMessage = """⚡️ Pembayaran dikirim oleh %s."""
|
||||
invalidInvoiceHelpMessage = """Apakah kamu memasukan invoice Lightning yang benar? Coba /send jika kamu mau mengirimkan ke pengguna Telegram atau alamat Lightning."""
|
||||
invoiceNoAmountMessage = """🚫 Tidak dapat membayar invoice tanpa jumlah."""
|
||||
insufficientFundsMessage = """🚫 Kekurangan dana. Kamu memiliki %d sat namun kamu memerlukan setidaknya %d sat."""
|
||||
feeReserveMessage = """⚠️ Mengirimkan seluruh saldo bisa gagal karena adanya biaya jaringan. Jika gagal, coba jumlah kirimnya dikurangi sedikit."""
|
||||
invoicePaymentFailedMessage = """🚫 Pembayaran gagal: %s"""
|
||||
invoiceUndefinedErrorMessage = """Tidak dapat membayar invoice."""
|
||||
confirmPayInvoiceMessage = """Apakah kamu mau mengirimkan pembayaran ini?\n\n💸 Jumlah: %d sat"""
|
||||
confirmPayAppendMemo = """\n✉️ %s"""
|
||||
payHelpText = """📖 Waduh, itu tidak berhasil. %s
|
||||
|
||||
*Usage:* `/pay <invoice>`
|
||||
*Example:* `/pay lnbc20n1psscehd...`"""
|
||||
|
||||
# DONATE
|
||||
|
||||
donationSuccess = """🙏 Terima kasih untuk donasi mu."""
|
||||
donationErrorMessage = """🚫 Waduh. Donasi gagal."""
|
||||
donationProgressMessage = """🧮 Menyiapkan donasi mu..."""
|
||||
donationFailedMessage = """🚫 Donasi gagal: %s"""
|
||||
donateEnterAmountMessage = """Apakah kamu sudah memasukkan jumlah?"""
|
||||
donateValidAmountMessage = """Apakah kamu memasukkan jumlah yang benar?"""
|
||||
donateHelpText = """📖 Waduh, itu tidak berhasil. %s
|
||||
|
||||
*Usage:* `/donate <jumlah>`
|
||||
*Example:* `/donate 1000`"""
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 Tidak dapat mengenali sebuah invoice Lightning invoice atau sebuah LNURL. Coba arahkan ke tengah QR code, potong foto kodenya, atau zoom in."""
|
||||
photoQrRecognizedMessage = """✅ QR code:
|
||||
`%s`"""
|
||||
|
||||
# LNURL
|
||||
|
||||
lnurlReceiveInfoText = """👇 Kamu dapat menggunakan LNURL statis ini untuk menerima pembayaran."""
|
||||
lnurlResolvingUrlMessage = """🧮 Menyelesaikan alamat..."""
|
||||
lnurlGettingUserMessage = """🧮 Mempersiapkan pembayaran..."""
|
||||
lnurlPaymentFailed = """🚫 Pembayaran gagal: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Jumlah tidak benar."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Jumlah harus diantara %d dan %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Kamu harus mengatur nama pengguna Telegram untuk menerima pembayaran melalui LNURL."""
|
||||
lnurlHelpText = """📖 Waduh, itu tidak berhasil. %s
|
||||
|
||||
*Usage:* `/lnurl [jumlah] <lnurl>`
|
||||
*Example:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL PENARIKAN
|
||||
|
||||
confirmLnurlWithdrawMessage = """Apakah anda ingin melakukan penarikan ini?\n\n💸 Jumlah: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Mempersiapkan penarikan..."""
|
||||
lnurlWithdrawFailed = """🚫 Penarikan gagal."""
|
||||
lnurlWithdrawCancelled = """🚫 Penarikan dibatalkan."""
|
||||
lnurlWithdrawSuccess = """✅ Penarikan diajukan."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Hubungkan dompet mu*
|
||||
|
||||
⚠️ Jangan pernah membagikan URL atau kode QR nya dengan siapa pun karena mereka akan bisa mengakses dana mu.
|
||||
|
||||
- *BlueWallet:* Tekan *New wallet*, *Import wallet*, *Scan atau import a file*, lalu scan kode QR nya.
|
||||
- *Zeus:* Salin URL dibawah, tekan *Add a new node*, *Import* (URL nya), *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Tidak dapat menghubungkan dompet mu. Silakan coba lagi nanti."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
inlineQueryFaucetTitle = """🚰 Membuat sebuah keran."""
|
||||
inlineQueryFaucetDescription = """Penggunaan: @%s faucet <kapasitas> <per_pengguna>"""
|
||||
inlineResultFaucetTitle = """🚰 Buat sebuah keran %d sat."""
|
||||
inlineResultFaucetDescription = """👉 Pencet disini untuk membuat sebuah keran di percakapan ini."""
|
||||
|
||||
inlineFaucetMessage = """Tekan ✅ untuk mengambil %d sat dari keran ini.
|
||||
|
||||
🚰 Tersisa: %d/%d sat (diberikan kepada %d/%d pengguna)
|
||||
%s"""
|
||||
inlineFaucetEndedMessage = """🚰 Keran kosong 🍺\n\n🏅 %d sat diberikan kepada %d pengguna."""
|
||||
inlineFaucetAppendMemo = """\n✉️ %s"""
|
||||
inlineFaucetCreateWalletMessage = """Bercakap dengan %s 👈 untuk mengelola dompet mu."""
|
||||
inlineFaucetCancelledMessage = """🚫 Keran dibatalkan."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 Jumlah untuk tiap pengguna tidak terbagi dari kapasitas."""
|
||||
inlineFaucetInvalidAmountMessage = """🚫 Jumlah tidak benar."""
|
||||
inlineFaucetSentMessage = """🚰 %d sat terkirim ke %s."""
|
||||
inlineFaucetReceivedMessage = """🚰 %s mengirimkan kamu %d sat."""
|
||||
inlineFaucetHelpFaucetInGroup = """Buat sebuah keran dalam sebuah grup dengan bot nya didalam atau gunakan 👉 perintah sebaris (/advanced untuk lebih lagi)."""
|
||||
inlineFaucetHelpText = """📖 Waduh, itu tidak berhasil. %s
|
||||
|
||||
*Usage:* `/faucet <kapasitas> <per_pengguna>`
|
||||
*Example:* `/faucet 210 21`"""
|
||||
|
||||
# INLINE SEND
|
||||
|
||||
inlineQuerySendTitle = """💸 Kirimkan pembayaran ke sebuah percakapan."""
|
||||
inlineQuerySendDescription = """Penggunaan: @%s send <jumlah> [<pengguna>] [<berita>]"""
|
||||
inlineResultSendTitle = """💸 Kirim %d sat."""
|
||||
inlineResultSendDescription = """👉 Pencet untuk mengirim %d sat ke percakapan ini."""
|
||||
|
||||
inlineSendMessage = """Tekan ✅ untuk menerima pembayaran dari %s.\n\n💸 Jumlah: %d sat"""
|
||||
inlineSendAppendMemo = """\n✉️ %s"""
|
||||
inlineSendUpdateMessageAccept = """💸 %d sat terkirim dari %s ke %s."""
|
||||
inlineSendCreateWalletMessage = """Bercakap dengan %s 👈 untuk mengelola dompet mu."""
|
||||
sendYourselfMessage = """📖 Kamu tidak dapat membayar diri mu sendiri."""
|
||||
inlineSendFailedMessage = """🚫 Pengiriman tidak berhasil."""
|
||||
inlineSendInvalidAmountMessage = """🚫 Jumlah harus lebih besar dari 0."""
|
||||
inlineSendBalanceLowMessage = """🚫 Saldo mu terlalu rendah."""
|
||||
|
||||
# INLINE RECEIVE
|
||||
|
||||
inlineQueryReceiveTitle = """🏅 Meminta pembayaran dalam sebuah percakapan."""
|
||||
inlineQueryReceiveDescription = """Penggunaan: @%s receive <jumlah> [<pengguna>] [<berita>]"""
|
||||
inlineResultReceiveTitle = """🏅 Menerima %d sat."""
|
||||
inlineResultReceiveDescription = """👉 Pencet untuk permintaan pembayaran sebesar %d sat."""
|
||||
|
||||
inlineReceiveMessage = """Tekan 💸 untuk membayar ke %s.\n\n💸 Jumlah: %d sat"""
|
||||
inlineReceiveAppendMemo = """\n✉️ %s"""
|
||||
inlineReceiveUpdateMessageAccept = """💸 %d sat terkirim oleh %s ke %s."""
|
||||
inlineReceiveCreateWalletMessage = """Bercakap dengan %s 👈 untuk mengelola dompet mu."""
|
||||
inlineReceiveYourselfMessage = """📖 Kamu tidak dapat membayar diri mu sendiri."""
|
||||
inlineReceiveFailedMessage = """🚫 Penerimaan gagal."""
|
||||
inlineReceiveCancelledMessage = """🚫 Penerimaan dibatalkan."""
|
||||
@@ -1,304 +0,0 @@
|
||||
# COMMANDS
|
||||
|
||||
helpCommandStr = """aiuto"""
|
||||
basicsCommandStr = """informazioni"""
|
||||
tipCommandStr = """mancia"""
|
||||
balanceCommandStr = """saldo"""
|
||||
sendCommandStr = """invia"""
|
||||
invoiceCommandStr = """invoice"""
|
||||
payCommandStr = """paga"""
|
||||
donateCommandStr = """dona"""
|
||||
advancedCommandStr = """avanzate"""
|
||||
transactionsCommandStr = """traduzioni"""
|
||||
logCommandStr = """log"""
|
||||
listCommandStr = """lista"""
|
||||
|
||||
linkCommandStr = """link"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """distribuzione"""
|
||||
|
||||
tipjarCommandStr = """salvadanaio"""
|
||||
receiveCommandStr = """ricevi"""
|
||||
hideCommandStr = """nascondi"""
|
||||
volcanoCommandStr = """vulcano"""
|
||||
showCommandStr = """mostra"""
|
||||
optionsCommandStr = """opzioni"""
|
||||
settingsCommandStr = """impostazioni"""
|
||||
saveCommandStr = """salva"""
|
||||
deleteCommandStr = """cancella"""
|
||||
infoCommandStr = """info"""
|
||||
|
||||
# NOTIFICATIONS
|
||||
|
||||
cantDoThatMessage = """Funzione non disponibile."""
|
||||
cantClickMessage = """Pulsante non selezionabile."""
|
||||
balanceTooLowMessage = """Saldo non sufficiente."""
|
||||
|
||||
# BUTTONS
|
||||
|
||||
sendButtonMessage = """✅ Invia"""
|
||||
payButtonMessage = """✅ Paga"""
|
||||
payReceiveButtonMessage = """💸 Paga"""
|
||||
receiveButtonMessage = """✅ Ricevi"""
|
||||
cancelButtonMessage = """🚫 Cancella"""
|
||||
collectButtonMessage = """✅ Incassa"""
|
||||
nextButtonMessage = """Prossimo"""
|
||||
backButtonMessage = """Indietro"""
|
||||
acceptButtonMessage = """Consenti"""
|
||||
denyButtonMessage = """Rifiuta"""
|
||||
tipButtonMessage = """Mancia"""
|
||||
revealButtonMessage = """Rivela"""
|
||||
showButtonMessage = """Mostra"""
|
||||
hideButtonMessage = """Nascondi"""
|
||||
joinButtonMessage = """Unisciti"""
|
||||
optionsButtonMessage = """Opzioni"""
|
||||
settingsButtonMessage = """Impostazioni"""
|
||||
saveButtonMessage = """Salva"""
|
||||
deleteButtonMessage = """Cancella"""
|
||||
infoButtonMessage = """Info"""
|
||||
|
||||
# HELP
|
||||
|
||||
helpMessage = """⚡️ *Wallet*
|
||||
_Questo bot è un Wallet Bitcoin Lightning con cui puoi inviare ricompense via Telegram. Per inviare, aggiungi il bot come partecipante a una chat di gruppo. L'unità di conto per questi invii di piccolo importo è il Satoshi (sat). 100,000,000 sat = 1 Bitcoin. Digita 📚 /basics per maggiori informazioni._
|
||||
|
||||
❤️ *Dona*
|
||||
_Questo bot non applica commissioni agli utenti, ma costa alcuni Satoshi gestirlo. Se ti piace, valuta se sostenere questo progetto con una donazione. Per donare, usa il comando_ `/donate 1000`
|
||||
|
||||
%s
|
||||
|
||||
⚙️ *Comandi*
|
||||
*/tip* 🏅 Rispondi così a un messaggio per inviare una mancia: `/tip <ammontare> [<memo>]`
|
||||
*/balance* 👑 Verifica il tuo saldo residuo: `/balance`
|
||||
*/send* 💸 Invia fondi a un utente: `/send <ammontare> @utente o utente@ln.tips [<memo>]`
|
||||
*/invoice* ⚡️ Ricevi attraverso Lightning: `/invoice <ammontare> [<memo>]`
|
||||
*/pay* ⚡️ Paga attraverso Lightning: `/pay <invoice>`
|
||||
*/donate* ❤️ Dona per supportare questo progetto: `/donate 1000`
|
||||
*/advanced* 🤖 Funzioni avanzate.
|
||||
*/help* 📖 Richiama questo elenco."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Info*"""
|
||||
infoYourLightningAddress = """Il tuo indirizzo Lightning è `%s`"""
|
||||
|
||||
basicsMessage = """🧡 *Bitcoin*
|
||||
_Bitcoin è la valuta di internet. È una rete libera e decentralizzata a cui tutti possono partecipare, senza una autorità di controllo centrale. Bitcoin è una moneta ma anche un sistema di pagamento più veloce, sicuro e inclusivo del sistema finanziario tradizionale._
|
||||
|
||||
🧮 *Economnics*
|
||||
_La più piccola unità in cui è divisibile un Bitcoin è un Satoshi (sat) e 100,000,000 sat equivalgono a 1 Bitcoin. Esistono solamente 21 milioni di Bitcoin. Il valore di Bitcoin espresso in valuta tradizionale può variare ogni giorno. In ogni caso, se la tua valuta di riferimento è Bitcoin, 1 sat varrà sempre 1 sat._
|
||||
|
||||
⚡️ *Lightning Network*
|
||||
_Lightning Network è un protocollo di pagamento che consente pagamenti in Bitcoin veloci ed economici, praticamente senza consumare energia. È il sistema che consentirà di diffondere Bitcoin a miliardi di persone nel mondo._
|
||||
|
||||
📲 *Lightning Wallets*
|
||||
_I tuoi fondi conservati in questo bot possono essere mandati a un altro wallet Lightning e viceversa. Altri wallet Lightning per il tuo smartphone sono_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (non-custodial), oppure_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(semplice da usare)_.
|
||||
|
||||
📄 *Open Source*
|
||||
_Questo bot è software libero e_ [open source](https://github.com/LightningTipBot/LightningTipBot) _. Puoi farlo girare sul tuo computer e usarlo per la tua comunità._
|
||||
|
||||
✈️ *Telegram*
|
||||
_Aggiungi questo bot a una chat di gruppo Telegram per inviare una /tip. Se concedi al bot i privilegi di amministratore della chat, il bot si occuperà automaticamente di eliminare i comandi inviati per tenere la chat pulita._
|
||||
|
||||
🏛 *Termini e condizioni*
|
||||
_Noi non siamo custodi dei tuoi fondi. Agiremo sempre nel tuo migliore interesse, ma siamo consapevoli che operare senza il riconoscimento formale dei Clienti (KYC) è un terreno accidentato finché non troviamo qualche soluzione alternativa. Qualsiasi ammontare caricato nel wallet sarà formalmente considerato una donazione. Non inviarci tutto il tuo denaro! Sii consapevole che questo bot è ancora in fase di sviluppo, e puoi usarlo a tuo rischio e pericolo._
|
||||
|
||||
❤️ *Dona*
|
||||
_Questo bot non applica commissioni agli utenti, ma costa alcuni Satoshi gestirlo. Se ti piace, valuta se sostenere questo progetto con una donazione. Per donare, usa il comando_ `/donate 1000`"""
|
||||
|
||||
helpNoUsernameMessage = """👋 Per favore imposta un nome utente Telegram."""
|
||||
|
||||
advancedMessage = """%s
|
||||
|
||||
👉 *Comandi in linea*
|
||||
*send* 💸 Invia alcuni sat a una chat: `%s send <ammontare> [<utente>] [<memo>]`
|
||||
*receive* 🏅 Richiedi un pagamento: `... receive <ammontare> [<utente>] [<memo>]`
|
||||
*faucet* 🚰 Crea una distribuzione: `... faucet <totale> <per_utente> [<memo>]`
|
||||
*tipjar* 🍯 Crea un tipjar: `... tipjar <totale> <per_utente> [<memo>]`
|
||||
|
||||
📖 Puoi usare i comandi in linea in ogni chat, anche nelle conversazioni private. Attendi un secondo dopo aver inviato un comando in linea e *clicca* sull'azione desiderata, non premere invio.
|
||||
|
||||
⚙️ *Comandi avanzati*
|
||||
*/link* 🔗 Crea un collegamento al tuo wallet [BlueWallet](https://bluewallet.io/) o [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Ricevi o paga un Lnurl: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Crea una distribuzione: `/faucet <totale> <per_utente>`
|
||||
*/tipjar* 🍯 Crea un tipjar: `/tipjar <totale> <per_utente>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Imposta un ammontare tra %d e %d sat."""
|
||||
enterAmountMessage = """💯 Imposta un ammontare."""
|
||||
enterUserMessage = """👤 Imposta un utente."""
|
||||
errorReasonMessage = """🚫 Errore: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Sto creando il tuo wallet..."""
|
||||
startWalletCreatedMessage = """🧮 Wallet creato."""
|
||||
startWalletReadyMessage = """✅ *Il tuo wallet è pronto.*"""
|
||||
startWalletErrorMessage = """🚫 Errore di inizializzazione del wallet. Riprova più tardi."""
|
||||
startNoUsernameMessage = """☝️ Sembra che tu non abbia un nome utente Telegram @username. Non è obbligatorio per utilizzare questo bot, ma consente di abilitare ulteriori funzioni. Per usare al meglio il tuo wallet, imposta un nome utente nelle impostazioni Telegram e poi inserisci /balance in modo che il bot possa aggiornarsi."""
|
||||
|
||||
# BALANCE
|
||||
|
||||
balanceMessage = """👑 *Il tuo saldo è:* %d sat"""
|
||||
balanceErrorMessage = """🚫 Non riesco a recupare il tuo saldo. Per favore riprova più tardi."""
|
||||
|
||||
# TIP
|
||||
|
||||
tipDidYouReplyMessage = """Hai risposto a un messaggio per inviare una mancia? Per rispondere a un messaggio, clicca con il tasto destro -> Rispondi sul tuo computer o fai swipe sul tuo smartphone. Se vuoi inviare direttamente a un altro utente, usa il comando /send."""
|
||||
tipInviteGroupMessage = """ℹ️ In ogni caso, puoi invitare questo bot in qualsiasi chat di gruppo per incominciare a inviare mance."""
|
||||
tipEnterAmountMessage = """Hai inserito un ammontare?"""
|
||||
tipValidAmountMessage = """Hai inserito un ammontare valido?"""
|
||||
tipYourselfMessage = """📖 Non puoi inviare una mancia a te stesso."""
|
||||
tipSentMessage = """💸 %d sat inviati a %s."""
|
||||
tipReceivedMessage = """🏅 %s ti ha inviato una mancia di %d sat."""
|
||||
tipErrorMessage = """🚫 Invio mancia non riuscito."""
|
||||
tipUndefinedErrorMsg = """Per favore riprova più tardi."""
|
||||
tipHelpText = """📖 Ops, non funziona. %s
|
||||
|
||||
*Usage:* `/tip <ammontare> [<memo>]`
|
||||
*Example:* `/tip 1000 meme fantastico!`"""
|
||||
|
||||
# SEND
|
||||
|
||||
sendValidAmountMessage = """Hai inserito un ammontare valido?"""
|
||||
sendUserHasNoWalletMessage = """🚫 L'utente %s non ha ancora creato un wallet."""
|
||||
sendSentMessage = """💸 %d sat inviati a %s."""
|
||||
sendPublicSentMessage = """💸 %d sat inviati da %s a %s."""
|
||||
sendReceivedMessage = """🏅 %s ti ha inviato %d sat."""
|
||||
sendErrorMessage = """🚫 Invio non riuscito."""
|
||||
confirmSendMessage = """Vuoi inviare un pagamento a %s?\n\n💸 Ammontare: %d sat"""
|
||||
confirmSendAppendMemo = """\n✉️ %s"""
|
||||
sendCancelledMessage = """🚫 Invio cancellato."""
|
||||
errorTryLaterMessage = """🚫 Errore. Per favore riprova più tardi."""
|
||||
sendSyntaxErrorMessage = """Hai specificato un ammontare e un destinatario? Puoi usare il comando /send per inviare sia a utenti Telegram come %s sia a un indirizzo Lightning del tipo LightningTipBot@ln.tips."""
|
||||
sendHelpText = """📖 Ops, non ha funzionato. %s
|
||||
|
||||
*Sintassi:* `/send <ammontare> <utente> [<memo>]`
|
||||
*Esempio:* `/send 1000 @LightningTipBot Amo questo bot ❤️`
|
||||
*Esempio:* `/send 1234 LightningTipBot@ln.tips`"""
|
||||
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Hai ricevuto %d sat."""
|
||||
invoiceEnterAmountMessage = """Hai inserito un ammontare?"""
|
||||
invoiceValidAmountMessage = """Hai inserito un ammontare valido?"""
|
||||
invoiceHelpText = """📖 Ops, non ha funzionato. %s
|
||||
|
||||
*Sintassi:* `/invoice <ammontare> [<memo>]`
|
||||
*Esempio:* `/invoice 1000 Grazie!`"""
|
||||
|
||||
# PAY
|
||||
|
||||
paymentCancelledMessage = """🚫 Pagamento cancellato."""
|
||||
invoicePaidMessage = """⚡️ Pagamento inviato."""
|
||||
invoicePublicPaidMessage = """⚡️ Pagamento inviato da %s."""
|
||||
invalidInvoiceHelpMessage = """Hai inserito una invoice Lightning valida? Prova /send se vuoi inviare fondi a un utente Telegram o a un indirizzo Lightning."""
|
||||
invoiceNoAmountMessage = """🚫 Non è possibile pagare questa invoice senza specificare un ammontare."""
|
||||
insufficientFundsMessage = """🚫 Fondi insufficienti. Hai in portafoglio %d sat ma servono almeno %d sat per l'invio."""
|
||||
feeReserveMessage = """⚠️ Inviare il tuo intero saldo potrebbe non essere possibile a causa della incidenza delle commissioni di rete. Se l'invio non va a buon fine, prova a inviare un ammontare leggermente inferiore."""
|
||||
invoicePaymentFailedMessage = """🚫 Pagamento non riuscito: %s"""
|
||||
invoiceUndefinedErrorMessage = """Non è stato possibile pagare questa invoice."""
|
||||
confirmPayInvoiceMessage = """Vuoi inviare questo pagamento?\n\n💸 Amount: %d sat"""
|
||||
confirmPayAppendMemo = """\n✉️ %s"""
|
||||
payHelpText = """📖 Ops, non ha funzionato. %s
|
||||
|
||||
*Sintassi:* `/pay <invoice>`
|
||||
*Esempio:* `/pay lnbc20n1psscehd...`"""
|
||||
|
||||
# DONATE
|
||||
|
||||
donationSuccess = """🙏 Grazie per la donazione."""
|
||||
donationErrorMessage = """🚫 Oh no, la tua donazione non è andata a buon fine."""
|
||||
donationProgressMessage = """🧮 Sto preparando la donazione..."""
|
||||
donationFailedMessage = """🚫 La donazione non è andata a buon fine: %s"""
|
||||
donateEnterAmountMessage = """Hai inserito un ammontare?"""
|
||||
donateValidAmountMessage = """Hai inserito un ammontare valido?"""
|
||||
donateHelpText = """📖 Ops, non ha funzionato. %s
|
||||
|
||||
*Sintassi:* `/donate <ammontare>`
|
||||
*Esepio:* `/donate 1000`"""
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 Non sono riuscito a riconoscere una invoice Lightning o un LNURL. Cerca cortesemente di centrare meglio il codice QR oppure prova a ritagliare o ingrandire l'immagine."""
|
||||
photoQrRecognizedMessage = """✅ Codice QR:
|
||||
`%s`"""
|
||||
|
||||
# LNURL
|
||||
|
||||
lnurlReceiveInfoText = """👇 Puoi usare questo LNURL statico per ricevere pagamenti."""
|
||||
lnurlResolvingUrlMessage = """🧮 Recupero indirizzo..."""
|
||||
lnurlGettingUserMessage = """🧮 Preparazione pagamento..."""
|
||||
lnurlPaymentFailed = """🚫 Pagamento non riuscito: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Ammontare non valido."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 L'ammontare deve essere compreso tra %d e %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Devi impostare un nome utente Telegram per ricevere pagamenti tramite un LNURL."""
|
||||
lnurlHelpText = """📖 Ops, non ha funzionato. %s
|
||||
|
||||
*Sintassi:* `/lnurl [ammontare] <lnurl>`
|
||||
*Esempio:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Collega il tuo wallet*
|
||||
|
||||
⚠️ Non mostrare mai la URL il codice QR, altrimenti qualcuno potrebbe avere accesso ai tuoi fondi.
|
||||
|
||||
- *BlueWallet:* Premi *+ (Aggiungi Portafoglio)*, *Importa portafoglio*, *scansionare un codice QR*, e scansiona il codice QR .
|
||||
- *Zeus:* Copia la URL qui sotto, premi *Add a new node*, *Import* (incolla la URL), *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Non sono riuscito a collegare il tuo wallet. Per favore riprova più tardi."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
inlineQueryFaucetTitle = """🚰 Crea una distribuzione di fondi."""
|
||||
inlineQueryFaucetDescription = """Sintassi: @%s faucet <totale> <per_utente>"""
|
||||
inlineResultFaucetTitle = """🚰 Crea una distribuzione per un totale di %d sat."""
|
||||
inlineResultFaucetDescription = """👉 Clicca qui per creare una distribuzione di fondi in questa chat."""
|
||||
|
||||
inlineFaucetMessage = """Premi ✅ per riscuotere %d sat da questa distribuzione.
|
||||
|
||||
🚰 Rimanente: %d/%d sat (distribuiti a %d/%d utenti)
|
||||
%s"""
|
||||
inlineFaucetEndedMessage = """🚰 Distribuzione completata 🍺\n\n🏅 %d sat distribuiti a %d utenti."""
|
||||
inlineFaucetAppendMemo = """\n✉️ %s"""
|
||||
inlineFaucetCreateWalletMessage = """Chatta con %s 👈 per gestire il tuo wallet."""
|
||||
inlineFaucetCancelledMessage = """🚫 Distribuzione cancellata."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 Ammontare per utente non è una frazione intera del totale."""
|
||||
inlineFaucetInvalidAmountMessage = """🚫 Ammontare non valido."""
|
||||
inlineFaucetSentMessage = """🚰 %d sat inviati a %s."""
|
||||
inlineFaucetReceivedMessage = """🚰 %s ti ha inviato %d sat."""
|
||||
inlineFaucetHelpFaucetInGroup = """Crea una distribuzione in un gruppo in cui sia presente il bot oppure usa il 👉 comando in linea (/advanced per ulteriori funzionalità)."""
|
||||
inlineFaucetHelpText = """📖 Ops, non ha funzionato. %s
|
||||
|
||||
*Sintassi:* `/faucet <totale> <per_utente>`
|
||||
*Esempio:* `/faucet 210 21`"""
|
||||
|
||||
# INLINE SEND
|
||||
|
||||
inlineQuerySendTitle = """💸 Invia pagamento in una chat."""
|
||||
inlineQuerySendDescription = """Sintassi: @%s send <ammontare> [<utente>] [<memo>]"""
|
||||
inlineResultSendTitle = """💸 Invio %d sat."""
|
||||
inlineResultSendDescription = """👉 Clicca per inviare %d sat in questa chat."""
|
||||
|
||||
inlineSendMessage = """Premi ✅ per ricevere un pagamento da %s.\n\n💸 Ammontare: %d sat"""
|
||||
inlineSendAppendMemo = """\n✉️ %s"""
|
||||
inlineSendUpdateMessageAccept = """💸 %d sat inviati da %s a %s."""
|
||||
inlineSendCreateWalletMessage = """Chatta con %s 👈 per gestire il tuo wallet."""
|
||||
sendYourselfMessage = """📖 Non puoi inviare un pagamento a te stesso."""
|
||||
inlineSendFailedMessage = """🚫 Invio non riuscito."""
|
||||
inlineSendInvalidAmountMessage = """🚫 L'ammontare deve essere maggiore di 0."""
|
||||
inlineSendBalanceLowMessage = """🚫 Il tuo saldo è insufficiente (%d sat)."""
|
||||
|
||||
# INLINE RECEIVE
|
||||
|
||||
inlineQueryReceiveTitle = """🏅 Richiedi un pagamento in una chat."""
|
||||
inlineQueryReceiveDescription = """Sintassi: @%s receive <ammontare> [<utente>] [<memo>]"""
|
||||
inlineResultReceiveTitle = """🏅 Ricevi %d sat."""
|
||||
inlineResultReceiveDescription = """👉 Clicca per richiedere un pagamento di %d sat."""
|
||||
|
||||
inlineReceiveMessage = """Premi 💸 per inviare un pagamento a %s.\n\n💸 Ammontare: %d sat"""
|
||||
inlineReceiveAppendMemo = """\n✉️ %s"""
|
||||
inlineReceiveUpdateMessageAccept = """💸 %d sat inviati da %s a %s."""
|
||||
inlineReceiveCreateWalletMessage = """Chatta con %s 👈 per gestire il tuo wallet."""
|
||||
inlineReceiveYourselfMessage = """📖 Non puoi inviare un pagamento a te stesso."""
|
||||
inlineReceiveFailedMessage = """🚫 Pagamento non riuscito."""
|
||||
inlineReceiveCancelledMessage = """🚫 Pagamento cancellato."""
|
||||
@@ -1,312 +0,0 @@
|
||||
# COMMANDS
|
||||
|
||||
helpCommandStr = """help"""
|
||||
basicsCommandStr = """basis"""
|
||||
tipCommandStr = """tip"""
|
||||
balanceCommandStr = """saldo"""
|
||||
sendCommandStr = """verzenden"""
|
||||
invoiceCommandStr = """factuur"""
|
||||
payCommandStr = """betalen"""
|
||||
donateCommandStr = """donatie"""
|
||||
advancedCommandStr = """geavanceerd"""
|
||||
transactionsCommandStr = """transacties"""
|
||||
logCommandStr = """log"""
|
||||
listCommandStr = """lijst"""
|
||||
|
||||
linkCommandStr = """connect"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """kraan"""
|
||||
|
||||
tipjarCommandStr = """donatiebox"""
|
||||
receiveCommandStr = """ontvangen"""
|
||||
hideCommandStr = """verbergen"""
|
||||
volcanoCommandStr = """vulkaan"""
|
||||
showCommandStr = """toon"""
|
||||
optionsCommandStr = """opties"""
|
||||
settingsCommandStr = """instellingen"""
|
||||
saveCommandStr = """save"""
|
||||
deleteCommandStr = """verwijderen"""
|
||||
infoCommandStr = """info"""
|
||||
|
||||
# NOTIFICATIONS
|
||||
|
||||
cantDoThatMessage = """Dat kun je niet doen."""
|
||||
cantClickMessage = """Je kunt niet op deze knop klikken."""
|
||||
balanceTooLowMessage = """Uw saldo is te laag."""
|
||||
|
||||
# BUTTONS
|
||||
|
||||
sendButtonMessage = """✅ Verzenden"""
|
||||
payButtonMessage = """✅ Betalen"""
|
||||
payReceiveButtonMessage = """💸 Betalen"""
|
||||
receiveButtonMessage = """✅ Ontvangen"""
|
||||
cancelButtonMessage = """🚫 Annuleren"""
|
||||
collectButtonMessage = """✅ Verzamelen"""
|
||||
nextButtonMessage = """Volgende"""
|
||||
backButtonMessage = """Terug"""
|
||||
acceptButtonMessage = """Accepteren"""
|
||||
denyButtonMessage = """Weigeren"""
|
||||
tipButtonMessage = """Tip"""
|
||||
revealButtonMessage = """Laat zijn"""
|
||||
showButtonMessage = """Toon"""
|
||||
hideButtonMessage = """Verbergen"""
|
||||
joinButtonMessage = """Deelnemen"""
|
||||
optionsButtonMessage = """Opties"""
|
||||
settingsButtonMessage = """Instellingen"""
|
||||
saveButtonMessage = """Save"""
|
||||
deleteButtonMessage = """Verwijderen"""
|
||||
infoButtonMessage = """Info"""
|
||||
|
||||
# HELP
|
||||
|
||||
helpMessage = """⚡️ *Wallet*
|
||||
_Deze bot is een Bitcoin Lightning wallet die tips kan sturen op Telegram. Om tips te geven, voeg de bot toe aan een groepschat. De basiseenheid van tips zijn Satoshis (sat). 100.000.000 sat = 1 Bitcoin. Type 📚 /basics voor meer._
|
||||
|
||||
❤️ *Doneren*
|
||||
_Deze bot brengt geen kosten in rekening maar kost Satoshis om te werken. Als je de bot leuk vindt, overweeg dan om dit project te steunen met een donatie. Om te doneren, gebruik_ `/donate 1000`
|
||||
|
||||
%s
|
||||
|
||||
⚙️ *opdrachten*
|
||||
*/tip* 🏅 Antwoord op een bericht aan tip: `/tip <bedrag> [<memo>]`
|
||||
*/balance* 👑 Controleer uw saldo: `/balance`
|
||||
*/send* 💸 Stuur geld naar een gebruiker: `/send <bedrag> @user of user@ln.tips [<memo>]`
|
||||
*/invoice* ⚡️ Ontvang met Lightning: `/invoice <bedrag> [<memo>]`
|
||||
*/pay* ⚡️ Betaal met Lightning: `/pay <invoice>`
|
||||
*/donate* ❤️ Doneer aan het project: `/donate 1000`
|
||||
*/advanced* 🤖 Geavanceerde functies.
|
||||
*/help* 📖 Lees deze hulp."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Info*"""
|
||||
infoYourLightningAddress = """Uw Lightning adres is `%s`"""
|
||||
|
||||
basicsMessage = """🧡 *Bitcoin*
|
||||
_Bitcoin is de munteenheid van het internet. Het functioneert zonder toestemming, is gedecentraliseerd en heeft geen meesters of een controlerende autoriteit. Bitcoin is gezond geld dat sneller, veiliger en inclusiever is dan het oude financiële systeem.
|
||||
|
||||
🧮 *Economie*
|
||||
_De kleinste eenheid van Bitcoin zijn Satoshis (sat) en 100.000.000 sat = 1 Bitcoin. Er zullen ooit maar 21 miljoen Bitcoin zijn. De fiatvalutawaarde van Bitcoin kan dagelijks veranderen. Echter, als u leeft op een Bitcoin-standaard zal 1 sat altijd gelijk zijn aan 1 sat._
|
||||
|
||||
⚡️ *Het Lightning Network*
|
||||
_Het Lightning Network is een betalingsprotocol dat snelle en goedkope Bitcoin-betalingen mogelijk maakt die bijna geen energie vergen. Het is wat Bitcoin schaalt naar de miljarden mensen over de hele wereld._
|
||||
|
||||
📲 *Lightning Wallets*
|
||||
_U kunt uw geld via deze bot naar elke andere Lightning Wallet in de wereld sturen. Aanbevolen Lightning wallets voor uw telefoon zijn_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (niet-custodiaal), of_ [Wallet van Satoshi](https://www.walletofsatoshi.com/) _(gemakkelijk)_.
|
||||
|
||||
📄 *Open Source*
|
||||
_Deze bot is gratis en_ [open source](https://github.com/LightningTipBot/LightningTipBot) _software. U kunt het op uw eigen computer draaien en in uw eigen gemeenschap gebruiken._
|
||||
|
||||
✈️ *Telegram*
|
||||
_Voeg deze bot toe aan je Telegram groep chat om berichten te /tip. Als je de bot admin maakt van de groep zal hij ook commando's opruimen om de chat netjes te houden._
|
||||
|
||||
🏛 *Voorwaarden*
|
||||
_Wij zijn geen bewaarder van uw fondsen. Wij zullen in uw belang handelen, maar we zijn ons er ook van bewust dat de situatie zonder KYC lastig is totdat we iets hebben uitgezocht. Elk bedrag dat u in uw portemonnee laadt, wordt beschouwd als een donatie. Geef ons niet al uw geld. Wees ervan bewust dat deze bot in beta ontwikkeling is. Gebruik op eigen risico.
|
||||
|
||||
❤️ *Doneren*
|
||||
_Deze bot brengt geen kosten in rekening maar kost satoshis om te werken. Als je de bot leuk vindt, overweeg dan om dit project te steunen met een donatie. Om te doneren, gebruik_ `/donate 1000`"""
|
||||
|
||||
helpNoUsernameMessage = """👋 Stel alstublieft een Telegram gebruikersnaam in."""
|
||||
|
||||
advancedMessage = """%s
|
||||
|
||||
👉 *Inline commands*
|
||||
*send* 💸 Stuur sats naar chat: `%s send <bedrag> [<user>] [<memo>]`
|
||||
*receive* 🏅 Verzoek om betaling: `... receive <bedrag> [<user>] [<memo>]`
|
||||
*faucet* 🚰 Maak een kraan: `... faucet <capacity> <per_user> [<memo>]`
|
||||
*tipjar* 🍯 Maak een tipjar: `... tipjar <capacity> <per_user> [<memo>]`
|
||||
|
||||
📖 Je kunt inline commando's in elke chat gebruiken, zelfs in privé gesprekken. Wacht een seconde na het invoeren van een inline commando en *klik* op het resultaat, druk niet op enter.
|
||||
|
||||
⚙️ *Geavanceerde opdrachten*
|
||||
*/link* 🔗 Koppel uw wallet aan [BlueWallet](https://bluewallet.io/) of [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl ontvangen of betalen: `/lnurl` of `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Maak een kraan: `/faucet <capacity> <per_user>`
|
||||
*/tipjar* 🍯 Maak een tipjar: `/tipjar <capacity> <per_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Voer een bedrag in tussen %d en %d sat."""
|
||||
enterAmountMessage = """💯 Voer een bedrag."""
|
||||
enterUserMessage = """👤 Voer een gebruiker."""
|
||||
errorReasonMessage = """🚫 Fout: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Uw wallet instellen..."""
|
||||
startWalletCreatedMessage = """🧮 Wallet gemaakt."""
|
||||
startWalletReadyMessage = """✅ *Uw wallet is klaar.*"""
|
||||
startWalletErrorMessage = """🚫 Fout bij het initialiseren van uw wallet. Probeer later opnieuw."""
|
||||
startNoUsernameMessage = """☝️ Het lijkt erop dat je nog geen Telegram @ gebruikersnaam hebt. Dat is niet erg, je hebt er geen nodig om deze bot te gebruiken. Echter, om beter gebruik te maken van je wallet, stel je een gebruikersnaam in bij de Telegram instellingen. Voer vervolgens /balance in, zodat de bot zijn gegevens over jou kan bijwerken."""
|
||||
|
||||
# BALANCE
|
||||
|
||||
balanceMessage = """👑 *Uw saldo:* %d sat"""
|
||||
balanceErrorMessage = """🚫 Kon uw saldo niet ophalen. Probeer het later nog eens."""
|
||||
|
||||
# TIP
|
||||
|
||||
tipDidYouReplyMessage = """Hebt u een bericht aan tip beantwoord? Om te antwoorden op een bericht, klik met de rechtermuisknop -> Beantwoorden op uw computer of veeg over het bericht op uw telefoon. Als je direct naar een andere gebruiker wilt sturen, gebruik dan het /send commando."""
|
||||
tipInviteGroupMessage = """ℹ️ Trouwens, je kan deze bot uitnodigen voor elke groep om daar te beginnen tippen."""
|
||||
tipEnterAmountMessage = """Heb je een bedrag ingevoerd?"""
|
||||
tipValidAmountMessage = """Heb je een geldig bedrag ingevoerd?"""
|
||||
tipYourselfMessage = """📖 Je kunt jezelf geen tip geven."""
|
||||
tipSentMessage = """💸 %d sat gestuurd naar %s."""
|
||||
tipReceivedMessage = """🏅 %s heeft je getipt %d sat."""
|
||||
tipErrorMessage = """🚫 Tip mislukt."""
|
||||
tipUndefinedErrorMsg = """probeer het later nog eens."""
|
||||
tipHelpText = """📖 Oeps, dat werkte niet. %s
|
||||
|
||||
*Usage:* `/tip <bedrag> [<memo>]`
|
||||
*Example:* `/tip 1000 Dank meme!`"""
|
||||
|
||||
# SEND
|
||||
|
||||
sendValidAmountMessage = """Heb je een geldig bedrag ingevoerd?"""
|
||||
sendUserHasNoWalletMessage = """🚫 Gebruiker %s heeft nog geen portemonnee aangemaakt."""
|
||||
sendSentMessage = """💸 %d sat verstuurd naar %s."""
|
||||
sendPublicSentMessage = """💸 %d sat verstuurd van %s naar %s."""
|
||||
sendReceivedMessage = """🏅 %s stuurde u %d sat."""
|
||||
sendErrorMessage = """🚫 Verzenden mislukt."""
|
||||
confirmSendMessage = """Wilt u betalen aan %s? bedrag: %d sat"""
|
||||
confirmSendAppendMemo = """\n✉️ %s"""
|
||||
sendCancelledMessage = """🚫 Geannuleerd verzenden."""
|
||||
errorTryLaterMessage = """🚫 Fout. Probeer het later nog eens."""
|
||||
sendSyntaxErrorMessage = """Heb je een bedrag en een ontvanger ingevoerd? U kunt het /send commando gebruiken om ofwel naar Telegram gebruikers te sturen zoals %s of naar een Lightning adres zoals LightningTipBot@ln.tips."""
|
||||
sendHelpText = """📖 Oeps, dat werkte niet. %s
|
||||
|
||||
*Usage:* `/send <bedrag> <user> [<memo>]`
|
||||
*Example:* `/send 1000 @LightningTipBot Ik hou gewoon van de bot ❤️`
|
||||
*Example:* `/send 1234 LightningTipBot@ln.tips`"""
|
||||
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Je hebt %d sat ontvangen ."""
|
||||
invoiceEnterAmountMessage = """Heb je een bedrag ingevoerd?"""
|
||||
invoiceValidAmountMessage = """Heeft u een geldig bedrag ingevoerd?"""
|
||||
invoiceHelpText = """📖 Oeps, dat werkte niet. %s
|
||||
|
||||
*Usage:* `/invoice <bedrag> [<memo>]`
|
||||
*Example:* `/invoice 1000 Dank je!`"""
|
||||
|
||||
# PAY
|
||||
|
||||
paymentCancelledMessage = """🚫 Betaling geannuleerd."""
|
||||
invoicePaidMessage = """⚡️ Betaling verzonden."""
|
||||
invoicePublicPaidMessage = """⚡️ Betaling verzonden door %s."""
|
||||
invalidInvoiceHelpMessage = """Heeft u een geldige Lightning factuur ingevoerd? Probeer /send als u wilt verzenden naar een Telegram gebruiker of Lightning address."""
|
||||
invoiceNoAmountMessage = """🚫 Kan facturen niet betalen zonder een bedrag."""
|
||||
insufficientFundsMessage = """🚫 Onvoldoende middelen. Je hebt %d sat maar je hebt minstens %d sat nodig."""
|
||||
feeReserveMessage = """⚠️ Het versturen van uw volledige saldo kan mislukken vanwege netwerkkosten. Als het mislukt, probeer dan een beetje minder te verzenden."""
|
||||
invoicePaymentFailedMessage = """🚫 Betaling mislukt: %s"""
|
||||
invoiceUndefinedErrorMessage = """Kon de factuur niet betalen."""
|
||||
confirmPayInvoiceMessage = """Wilt u deze betaling sturen?\n\n💸 bedrag: %d sat"""
|
||||
confirmPayAppendMemo = """\n✉️ %s"""
|
||||
payHelpText = """📖 Oeps, dat werkte niet. %s
|
||||
|
||||
*Usage:* `/pay <invoice>`
|
||||
*Example:* `/pay lnbc20n1psscehd...`"""
|
||||
|
||||
# DONATE
|
||||
|
||||
donationSuccess = """🙏 Dank u voor uw donatie."""
|
||||
donationErrorMessage = """🚫 Oh nee. Donatie mislukt."""
|
||||
donationProgressMessage = """🧮 Preparing your donation..."""
|
||||
donationFailedMessage = """🚫 Donatie mislukt: %s"""
|
||||
donateEnterAmountMessage = """Heeft u een bedrag ingevoerd?"""
|
||||
donateValidAmountMessage = """Heeft u een geldig bedrag ingevoerd?"""
|
||||
donateHelpText = """📖 Oeps, dat werkte niet. %s
|
||||
|
||||
*Usage:* `/donate <bedrag>`
|
||||
*Example:* `/donate 1000`"""
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 Kon een Lightning factuur of een LNURL niet herkennen. Probeer de QR code te centreren, de foto bij te snijden, of in te zoomen."""
|
||||
photoQrRecognizedMessage = """✅ QR code:
|
||||
`%s`"""
|
||||
|
||||
# LNURL
|
||||
|
||||
lnurlReceiveInfoText = """👇 U kunt deze statische LNURL gebruiken om betalingen te ontvangen."""
|
||||
lnurlResolvingUrlMessage = """🧮 Opzoeken adres..."""
|
||||
lnurlGettingUserMessage = """🧮 Voorbereiding van betaling..."""
|
||||
lnurlPaymentFailed = """🚫 Betaling mislukt: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Ongeldig bedrag."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Bedrag moet liggen tussen %d en %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 U moet een Telegram gebruikersnaam instellen om betalingen te ontvangen via LNURL."""
|
||||
lnurlHelpText = """📖 Oeps, dat werkte niet. %s
|
||||
|
||||
*Usage:* `/lnurl [bedrag] <lnurl>`
|
||||
*Example:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """Wilt u deze opname maken?💸 Bedrag: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Opname aan het voorbereiden..."""
|
||||
lnurlWithdrawFailed = """🚫 Opname mislukt."""
|
||||
lnurlWithdrawCancelled = """🚫 Opname geannuleerd."""
|
||||
lnurlWithdrawSuccess = """✅ Opname aangevraagd."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Koppel uw wallet*
|
||||
|
||||
⚠️ Deel nooit de URL of de QR code met iemand anders of zij zullen toegang krijgen tot uw fondsen.
|
||||
|
||||
- *BlueWallet:* Druk op *Nieuwe wallet*, *Import wallet*, *Scan of importeer een bestand*, en scan de QR code.
|
||||
- *Zeus:* Kopieer de URL hieronder, druk op *Voeg een nieuw knooppunt toe*, *Import* (de URL), *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Uw wallet kon niet gelinkt worden. Probeer het later opnieuw."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
inlineQueryFaucetTitle = """🚰 Maak een kraan."""
|
||||
inlineQueryFaucetDescription = """Gebruik: @%s faucet <capacity> <per_user>"""
|
||||
inlineResultFaucetTitle = """🚰 Maak een %d sat kraan."""
|
||||
inlineResultFaucetDescription = """👉 Klik hier om een kraan in deze chat te maken.."""
|
||||
|
||||
inlineFaucetMessage = """Druk op ✅ om %d sat te verzamelen van deze kraan.
|
||||
|
||||
🚰 Remaining: %d/%d sat (given to %d/%d users)
|
||||
%s"""
|
||||
inlineFaucetEndedMessage = """🚰 kraan leeg 🍺🏅 %d sat gegeven aan %d gebruikers."""
|
||||
inlineFaucetAppendMemo = """\n✉️ %s"""
|
||||
inlineFaucetCreateWalletMessage = """Chat met %s 👈 om uw wallet te beheren."""
|
||||
inlineFaucetCancelledMessage = """🚫 kraan geannuleerd."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 Per gebruiker bedrag niet deelbaar van capaciteit."""
|
||||
inlineFaucetInvalidAmountMessage = """🚫 Ongeldig bedrag."""
|
||||
inlineFaucetSentMessage = """🚰 %d sat gestuurd naar %s."""
|
||||
inlineFaucetReceivedMessage = """🚰 %s stuurde je %d sat."""
|
||||
inlineFaucetHelpFaucetInGroup = """Maak een kraan in een groep met de bot erin of gebruik 👉 inline commando (/advanced voor meer)."""
|
||||
inlineFaucetHelpText = """📖 Oeps, dat werkte niet. %s
|
||||
|
||||
*Usage:* `/faucet <capaciteit> <per_gebruiker>`
|
||||
*Example:* `/faucet 210 21`"""
|
||||
|
||||
# INLINE VERZENDEN
|
||||
|
||||
inlineQuerySendTitle = """💸 Stuur betaling naar een chat."""
|
||||
inlineQuerySendDescription = """Gebruik: @%s send <bedrag> [<user>] [<memo>]"""
|
||||
inlineResultSendTitle = """💸 Stuur %d sat."""
|
||||
inlineResultSendDescription = """👉 Klik om %d sat naar deze chat te sturen."""
|
||||
|
||||
inlineSendMessage = """Druk op ✅ om de betaling van %s te ontvangen.\n💸 Bedrag: %d sat"""
|
||||
inlineSendAppendMemo = """\n✉️ %s"""
|
||||
inlineSendUpdateMessageAccept = """💸 %d verzonden van %s naar %s."""
|
||||
inlineSendCreateWalletMessage = """Chat met %s 👈 om uw wallet te beheren."""
|
||||
sendYourselfMessage = """📖 Je kunt niet aan jezelf betalen."""
|
||||
inlineSendFailedMessage = """🚫 verzenden mislukt."""
|
||||
inlineSendInvalidAmountMessage = """🚫 Bedrag moet groter zijn dan 0."""
|
||||
inlineSendBalanceLowMessage = """🚫 Uw saldo is te laag."""
|
||||
|
||||
# INLINE RECEIVE
|
||||
|
||||
inlineQueryReceiveTitle = """🏅 Vraag een betaling in een chat."""
|
||||
inlineQueryReceiveDescription = """Gebruik: @%s receive <bedrag> [<user>] [<memo>]"""
|
||||
inlineResultReceiveTitle = """🏅 Ontvang %d sat."""
|
||||
inlineResultReceiveDescription = """👉 Klik om een betaling van %d sat aan te vragen."""
|
||||
|
||||
inlineReceiveMessage = """Druk op 💸 om te betalen aan %s.\n💸 Bedrag: %d sat"""
|
||||
inlineReceiveAppendMemo = """\n✉️ %s"""
|
||||
inlineReceiveUpdateMessageAccept = """💸 %d sat verstuurd van %s naar %s."""
|
||||
inlineReceiveCreateWalletMessage = """Chat met %s 👈 om uw wallet te beheren."""
|
||||
inlineReceiveYourselfMessage = """📖 Je kunt niet aan jezelf betalen."""
|
||||
inlineReceiveFailedMessage = """🚫 Ontvangst mislukt."""
|
||||
inlineReceiveCancelledMessage = """🚫 Ontvangen geannuleerd."""
|
||||
@@ -1,336 +0,0 @@
|
||||
# COMMANDS
|
||||
|
||||
helpCommandStr = """ajuda"""
|
||||
basicsCommandStr = """conceitos"""
|
||||
tipCommandStr = """gorjeta"""
|
||||
balanceCommandStr = """saldo"""
|
||||
sendCommandStr = """enviar"""
|
||||
invoiceCommandStr = """fatura"""
|
||||
payCommandStr = """pagar"""
|
||||
donateCommandStr = """doar"""
|
||||
advancedCommandStr = """avançado"""
|
||||
transactionsCommandStr = """transações"""
|
||||
logCommandStr = """log"""
|
||||
listCommandStr = """lista"""
|
||||
|
||||
linkCommandStr = """enlace"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """torneira"""
|
||||
|
||||
tipjarCommandStr = """cofrinho"""
|
||||
receiveCommandStr = """receber"""
|
||||
hideCommandStr = """ocultar"""
|
||||
volcanoCommandStr = """vulcão"""
|
||||
showCommandStr = """mostrar"""
|
||||
optionsCommandStr = """opções"""
|
||||
settingsCommandStr = """configurações"""
|
||||
saveCommandStr = """salvar"""
|
||||
deleteCommandStr = """apagar"""
|
||||
infoCommandStr = """info"""
|
||||
|
||||
# NOTIFICATIONS
|
||||
|
||||
cantDoThatMessage = """Não se pode fazer isso."""
|
||||
cantClickMessage = """Não se pode clicar neste botão."""
|
||||
balanceTooLowMessage = """Seu saldo é muito baixo."""
|
||||
|
||||
# BUTTONS
|
||||
|
||||
sendButtonMessage = """✅ Enviar"""
|
||||
payButtonMessage = """✅ Pagar"""
|
||||
payReceiveButtonMessage = """💸 Pagar"""
|
||||
receiveButtonMessage = """✅ Receber"""
|
||||
cancelButtonMessage = """🚫 Cancelar"""
|
||||
collectButtonMessage = """✅ Cobrar"""
|
||||
nextButtonMessage = """Seguinte"""
|
||||
backButtonMessage = """Voltar"""
|
||||
acceptButtonMessage = """Aceitar"""
|
||||
denyButtonMessage = """Negar"""
|
||||
tipButtonMessage = """Gorjeta"""
|
||||
revealButtonMessage = """Revelar"""
|
||||
showButtonMessage = """Mostrar"""
|
||||
hideButtonMessage = """Ocultar"""
|
||||
joinButtonMessage = """Unir"""
|
||||
optionsButtonMessage = """Opções"""
|
||||
settingsButtonMessage = """Configurações"""
|
||||
saveButtonMessage = """Salvar"""
|
||||
deleteButtonMessage = """Apagar"""
|
||||
infoButtonMessage = """Info"""
|
||||
|
||||
# HELP
|
||||
|
||||
helpMessage = """⚡️ *Carteira*
|
||||
_Este bot é uma carteira Bitcoin Lightning que pode enviar gorjetas via Telegram. Para dar gorjetas, adicione o bot a um bate-papo em grupo. A unidade básica das gorjetas é Satoshis (sat). 100.000.000 sat = 1 Bitcoin. Digite 📚 /basics para saber mais._
|
||||
|
||||
❤️ *Doar*
|
||||
_Este bot não cobra nenhuma comissão, mas custa Satoshis para funcionar. Se você gosta do bot, por favor, considere apoiar este projeto com uma doação. Para doar, utilize_ `/donate 1000`.
|
||||
|
||||
%s
|
||||
|
||||
⚙️ *Comandos*
|
||||
*/tip* 🏅 Responder uma mensagem para dar uma gorjeta: `/tip <quantidade> [<memo>]`
|
||||
*/balance* 👑 Confira seu saldo: `/balance`.
|
||||
*/send* 💸 Enviar dinheiro para um usuário: `/send <quantidade> @user ou user@ln.tips [<memo>]`
|
||||
*/invoice* ⚡️ Receber com Lightning: `/invoice <quantidade> [<memo>]`
|
||||
*/pay* ⚡️ Pagar com Lightning: `/pay <fatura>`
|
||||
*/donate* ❤️ Doar ao projeto: `/donate 1000`
|
||||
*/advanced* 🤖 Funções avançadas.
|
||||
*/help* 📖 Ler esta ajuda."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Info*"""
|
||||
infoYourLightningAddress = """Seu Lightning Address _(Endereço Lightning)_ é `%s`."""
|
||||
|
||||
basicsMessage = """🧡 *Bitcoin*
|
||||
_Bitcoin é a moeda da Internet. É uma moeda sem permissão, descentralizada, sem proprietários e sem autoridade de controle. Bitcoin é dinheiro sólido, mais rápido, mais seguro e mais inclusivo do que o sistema financeiro fiat._
|
||||
|
||||
🧮 *Economia*
|
||||
_A menor unidade de Bitcoin é Satoshis (sat) e 100.000.000 sat = 1 Bitcoin. Haverá apenas 21 milhões de Bitcoin. O valor do Bitcoin em moeda fiduciária pode mudar diariamente. No entanto, se você vive no padrão Bitcoin, 1 sat será sempre 1 sat._
|
||||
|
||||
⚡️ *A Rede Lightning (Relâmpago)*
|
||||
_A rede Lightning é um protocolo de pagamento que permite que os pagamentos Bitcoin sejam feitos de forma rápida e econômica, com consumo mínimo de energia. É o que faz o Bitcoin escalar para bilhões de pessoas em todo o mundo._
|
||||
|
||||
📲 *Carteiras Lightning (Relâmpago)*
|
||||
_Seu dinheiro neste bot pode ser enviado para qualquer outra carteira da Lightning e vice versa. As carteiras Lightning recomendadas para seu telefone são_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (não-custodial), ou_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(fácil)_.
|
||||
|
||||
📄 *Código aberto*
|
||||
_Este bot é gratuito e de_ [Código aberto](https://github.com/LightningTipBot/LightningTipBot)_. Você pode executá-lo no seu próprio computador e utilizá-lo na sua própria comunidade._
|
||||
|
||||
✈️ *Telegram*
|
||||
_Adicione este bot ao seu bate-papo de grupo de Telegram para enviar dinheiro usando o comando /tip. Se você fizer do bot o administrador do grupo, ele também limpará os comandos para manter o bate-papo arrumado._
|
||||
|
||||
🏛 *Termos*
|
||||
_Nós não somos custódios do seu dinheiro. Atuaremos no seu melhor interesse, mas também estamos conscientes de que a situação sem KYC é complicada até encontrarmos uma solução ótima. Qualquer quantia que você colocar na sua carteira será considerada uma doação. Não ponha todo o seu dinheiro. Favor observar que este bot está em desenvolvimento beta. Use-o pela sua própria conta e risco._
|
||||
|
||||
❤️ *Doar*
|
||||
_Este bot não cobra nenhuma comissão, mas custa satoshis para funcionar. Se você gosta do bot, por favor, considere apoiar este projeto com uma doação. Para doar, utilize_ `/donate 1000`."""
|
||||
|
||||
helpNoUsernameMessage = """👋 Por favor, digite um nome de usuário do Telegram."""
|
||||
|
||||
advancedMessage = """%s
|
||||
|
||||
👉 *Comandos Inline*
|
||||
*send* 💸 Enviar sats ao bate-papo: `%s send <quantidade> [<usuário>] [<memo>]`
|
||||
*receive* 🏅 Solicite um pagamento: `... receive <quantidade> [<usuário>] [<memo>]`
|
||||
*faucet* 🚰 Criar uma torneira: `... faucet <capacidade> <por_usuário> [<memo>]`
|
||||
*tipjar* 🍯 Criar uma tipjar: `... tipjar <capacidade> <por_usuário> [<memo>]`
|
||||
|
||||
📖 Você pode usar comandos _inline_ em todas as conversas, mesmo em conversas privadas. Espere um segundo após inserir um comando _inline_ e *clique* no resultado, não pressione enter.
|
||||
|
||||
⚙️ *Comandos avançados*
|
||||
*/link* 🔗 Vincule sua carteira a [ BlueWallet ](https://bluewallet.io/) ou [ Zeus ](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Receber ou pagar com lnurl: `/lnurl` o `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Criar uma torneira: `/faucet <capacidade> <por_usuário>`
|
||||
*/tipjar* 🍯 Criar uma tipjar: `/tipjar <capacidade> <por_usuário>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Insira uma quantia entre %d e %d sat."""
|
||||
enterAmountMessage = """💯 Insira uma quantia."""
|
||||
enterUserMessage = """👤 Insira um usuário."""
|
||||
errorReasonMessage = """🚫 Erro: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Preparando sua carteira..."""
|
||||
startWalletCreatedMessage = """🧮 Carteira criada."""
|
||||
startWalletReadyMessage = """✅ *Sua carteira está pronta.*"""
|
||||
startWalletErrorMessage = """🚫 Erro ao iniciar sua carteira. Por favor, tente novamente mais tarde."""
|
||||
startNoUsernameMessage = """☝️ Parece que você ainda não tem um @nomedeusuário no Telegram. Tudo bem, você não precisa de um para usar este bot. Porém, para fazer melhor uso de sua carteira, defina um nome de usuário nas suas configurações de Telegram. Depois, entre /balance para que o bot possa atualizar seu registro de você."""
|
||||
|
||||
# BALANCE
|
||||
|
||||
balanceMessage = """👑 *Seu saldo:* %d sat"""
|
||||
balanceErrorMessage = """🚫 Seu saldo não pôde ser recuperado. Por favor, tente novamente mais tarde."""
|
||||
|
||||
# TIP
|
||||
|
||||
tipDidYouReplyMessage = """Você já respondeu em uma mensagem para dar gorjeta? Para responder qualquer mensagem, clique com o botão direito do mouse -> Responder no seu computador ou deslize a mensagem no seu telefone. Se você quiser enviar diretamente para outro usuário, use o comando /send."""
|
||||
tipInviteGroupMessage = """ℹ️ A propósito, você pode convidar este bot a qualquer grupo para começar a dar gorjetas lá."""
|
||||
tipEnterAmountMessage = """Você inseriu uma quantia?"""
|
||||
tipValidAmountMessage = """Você inseriu uma quantia válida?"""
|
||||
tipYourselfMessage = """📖 Você não pode se dar gorjetas."""
|
||||
tipSentMessage = """💸 %d sat enviado a %s."""
|
||||
tipReceivedMessage = """🏅 %s lhe deu uma gorjeta de %d sat."""
|
||||
tipErrorMessage = """🚫 A gorjeta falhou."""
|
||||
tipUndefinedErrorMsg = """Por favor, tente mais tarde"""
|
||||
tipHelpText = """📖 Opa, isso não funcionou. %s
|
||||
|
||||
*Uso:* `/tip <quantidade> [<memo>]`
|
||||
*Exemplo:* `/tip 1000 Meme ruim!`"""
|
||||
|
||||
# SEND
|
||||
|
||||
sendValidAmountMessage = """Você inseriu uma quantia válida?"""
|
||||
sendUserHasNoWalletMessage = """🚫 O usuário %s ainda não criou uma carteira."""
|
||||
sendSentMessage = """💸 %d sat enviado a %s."""
|
||||
sendPublicSentMessage = """💸 %d sat enviado(s) de %s a %s."""
|
||||
sendReceivedMessage = """🏅 %s lhe enviou %d sat."""
|
||||
sendErrorMessage = """🚫 Envio sem sucesso."""
|
||||
confirmSendMessage = """Deseja pagar %s?\n\n💸 Quantia: %d sat"""
|
||||
confirmSendAppendMemo = """\n✉️ %s"""
|
||||
sendCancelledMessage = """🚫 Envio cancelado."""
|
||||
errorTryLaterMessage = """🚫 Erro. Por favor, tente mais tarde."""
|
||||
sendSyntaxErrorMessage = """Você já inseriu uma quantia e um destinatário? Você pode usar o comando /send para enviar aos usuários de Telegram como %s ou para um Endereço Lightning como LightningTipBot@ln.tips."""
|
||||
sendHelpText = """📖 Opa, isso não funcionou. %s
|
||||
|
||||
*Uso:* `/send <quantidade> <usuário> [<memo>]`
|
||||
*Exemplo:* `/send 1000 @LightningTipBot Gosto do bot ❤️`.
|
||||
*Exemplo:* `/send 1234 LightningTipBot@ln.tips`"""
|
||||
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Recebeu %d sat."""
|
||||
invoiceEnterAmountMessage = """Você inseriu uma quantia?"""
|
||||
invoiceValidAmountMessage = """Você inseriu uma quantia válida?"""
|
||||
invoiceHelpText = """📖 Opa, isso não funcionou. %s
|
||||
|
||||
*Uso:* `/invoice <quantidade> [<memo>]`
|
||||
*Exemplo:* `/invoice 1000 Obrigado!`"""
|
||||
|
||||
# PAY
|
||||
|
||||
paymentCancelledMessage = """🚫 Pagamento cancelado."""
|
||||
invoicePaidMessage = """⚡️ Pagamento enviado."""
|
||||
invoicePublicPaidMessage = """⚡️ Pagamento enviado por %s."""
|
||||
invalidInvoiceHelpMessage = """Você já inseriu uma fatura Lightning válida? Tente /send se você quiser enviar a um usuário de Telegram ou a um endereço de Lightning."""
|
||||
invoiceNoAmountMessage = """🚫 As contas não podem ser pagas sem um valor."""
|
||||
insufficientFundsMessage = """🚫 Dinheiro insuficiente. Tem %d sat mas precisa pelo menos %d sat."""
|
||||
feeReserveMessage = """⚠️ O envio de todo o saldo pode falhar devido às taxas de rede. Se falhar, tente enviar um pouco menos."""
|
||||
invoicePaymentFailedMessage = """🚫 Falha no pagamento: %s"""
|
||||
invoiceUndefinedErrorMessage = """A fatura não pôde ser paga."""
|
||||
confirmPayInvoiceMessage = """Você quer enviar este pagamento?\n\n💸 Quantia: %d sat"""
|
||||
confirmPayAppendMemo = """\n✉️ %s"""
|
||||
payHelpText = """📖 Opa, isso não funcionou. %s
|
||||
|
||||
*Uso:* `/pay <fatura>`
|
||||
*Exemplo:* `/pay lnbc20n1psscehd...`"""
|
||||
|
||||
# DONATE
|
||||
|
||||
donationSuccess = """🙏 Obrigado pela sua doação."""
|
||||
donationErrorMessage = """🚫 Ó, não. Doação sem sucesso."""
|
||||
donationProgressMessage = """🧮 Preparando sua doação..."""
|
||||
donationFailedMessage = """🚫 Doação sem sucesso: %s"""
|
||||
donateEnterAmountMessage = """Você inseriu uma quantia?"""
|
||||
donateValidAmountMessage = """Você inseriu uma quantia válida?"""
|
||||
donateHelpText = """📖 Opa, isso não funcionou. %s
|
||||
|
||||
*Uso:* `/donate <quantidade>`
|
||||
*Exemplo:* `/donate 1000`"""
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 Uma fatura de Lightning ou LNURL não pôde ser reconhecida. Tente centralizar o código QR, cortando ou aumentando a foto."""
|
||||
photoQrRecognizedMessage = """✅ Código QR:
|
||||
`%s`"""
|
||||
|
||||
# LNURL
|
||||
|
||||
lnurlReceiveInfoText = """👇 Você pode usar este LNURL estático para receber pagamentos."""
|
||||
lnurlResolvingUrlMessage = """🧮 Solucionando o endereço..."""
|
||||
lnurlGettingUserMessage = """🧮 Preparando o pagamento..."""
|
||||
lnurlPaymentFailed = """🚫 Falha no pagamento: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Quantia inválida."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 A quantia deve estar entre %d e %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Você precisa configurar um nome de usuário de Telegram para receber pagamentos através do LNURL."""
|
||||
lnurlHelpText = """📖 Opa, isso não funcionou. %s
|
||||
|
||||
*Uso:* `/lnurl [quantidade] <lnurl>`
|
||||
*Exemplo:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """Você quer fazer esse saque?\n💸 Quantia: %d sat"""
|
||||
lnurlPreparingWithdraw = """🧮 Preparando o saque..."""
|
||||
lnurlWithdrawFailed = """🚫 Saque falhou."""
|
||||
lnurlWithdrawCancelled = """🚫 Saque cancelado."""
|
||||
lnurlWithdrawSuccess = """✅ Saque solicitado."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Vincule sua carteira*
|
||||
|
||||
⚠️ Nunca compartilhe a URL ou o código QR com ninguém ou eles poderão acessar seus fundos..
|
||||
|
||||
- *BlueWallet:* Toque em *Nova carteira*, *Importar carteira*, *Escanear ou importar um arquivo*, e escanear o código QR.
|
||||
- *Zeus:* Copie a URL abaixo, clique *Adicionar um novo nodo*, *Importar* (a URL), *Salvar configuração do nodo*."""
|
||||
couldNotLinkMessage = """🚫 Sua carteira não poderia ser ligada. Por favor, tente novamente mais tarde."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
inlineQueryFaucetTitle = """🚰 Crie uma torneira."""
|
||||
inlineQueryFaucetDescription = """Uso: @%s faucet <capacidade> <por_usuário>"""
|
||||
inlineResultFaucetTitle = """🚰 Criar uma torneira %d sat."""
|
||||
inlineResultFaucetDescription = """👉 Aperte aqui para criar uma torneira neste chat."""
|
||||
|
||||
inlineFaucetMessage = """Aperte ✅ para coletar %d sat desta torneira.
|
||||
|
||||
🚰 Restante: %d/%d sat (para %d/%d usuários)
|
||||
%s"""
|
||||
inlineFaucetEndedMessage = """🚰 Torneira vazia 🍺\n\n🏅 %d sat para %d usuários."""
|
||||
inlineFaucetAppendMemo = """\n✉️ %s"""
|
||||
inlineFaucetCreateWalletMessage = """Bate-papo com %s 👈 para administrar sua carteira."""
|
||||
inlineFaucetCancelledMessage = """🚫 Torneira cancelada."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 A quantia por usuário não é divisória da capacidade."""
|
||||
inlineFaucetInvalidAmountMessage = """🚫 Quantia inválida."""
|
||||
inlineFaucetSentMessage = """🚰 %d sat enviado(s) a %s."""
|
||||
inlineFaucetReceivedMessage = """🚰 %s lhe enviou %d sat."""
|
||||
inlineFaucetHelpFaucetInGroup = """Criar uma torneira em grupo com o bot dentro ou usar o 👉 comando_inline_ (/advanced para mais)."""
|
||||
inlineFaucetHelpText = """📖 Opa, isso não funcionou. %s
|
||||
|
||||
*Uso:* `/faucet <capacidad> <por_usuário>`
|
||||
*Exemplo:* `/faucet 210 21`"""
|
||||
|
||||
# INLINE SEND
|
||||
|
||||
inlineQuerySendTitle = """💸 Enviar pagamento para um bate-papo."""
|
||||
inlineQuerySendDescription = """Uso: @%s send <quantia> [<usuário>] [<memo>]"""
|
||||
inlineResultSendTitle = """💸 Enviar %d sat."""
|
||||
inlineResultSendDescription = """👉 Clique para enviar %d sat neste bate-papo."""
|
||||
|
||||
inlineSendMessage = """Clique ✅ para receber o pagamento de %s.\n\n💸 Quantidade: %d sat"""
|
||||
inlineSendAppendMemo = """\n✉️ %s"""
|
||||
inlineSendUpdateMessageAccept = """💸 %d sat enviado de %s a %s."""
|
||||
inlineSendCreateWalletMessage = """Bate-papo com %s 👈 para administrar sua carteira."""
|
||||
sendYourselfMessage = """📖 Você não pode pagar a si mesmo."""
|
||||
inlineSendFailedMessage = """🚫 Envio sem sucesso."""
|
||||
inlineSendInvalidAmountMessage = """🚫 A quantia deve ser maior do que 0."""
|
||||
inlineSendBalanceLowMessage = """🚫 Seu saldo é muito baixo."""
|
||||
|
||||
# INLINE RECEIVE
|
||||
|
||||
inlineQueryReceiveTitle = """🏅 Solicite um pagamento em um bate-papo."""
|
||||
inlineQueryReceiveDescription = """Uso: @%s receive <quantidade> [<usuário>] [<memo>]"""
|
||||
inlineResultReceiveTitle = """🏅 Receber %d sat."""
|
||||
inlineResultReceiveDescription = """👉 Clique para solicitar um pagamento de %d sat."""
|
||||
|
||||
inlineReceiveMessage = """Clique 💸 para pagar a %s.\n\n💸 Quantia: %d sat"""
|
||||
inlineReceiveAppendMemo = """\n✉️ %s"""
|
||||
inlineReceiveUpdateMessageAccept = """💸 %d sat enviado de %s a %s."""
|
||||
inlineReceiveCreateWalletMessage = """Bate-papo com %s 👈 para administrar sua carteira."""
|
||||
inlineReceiveYourselfMessage = """📖 Você não pode pagar a si mesmo."""
|
||||
inlineReceiveFailedMessage = """🚫 O recebimento falhou."""
|
||||
inlineReceiveCancelledMessage = """🚫 Recepção cancelada."""
|
||||
|
||||
# TIPJAR
|
||||
|
||||
inlineQueryTipjarTitle = """🍯 Criar um cofrinho."""
|
||||
inlineQueryTipjarDescription = """Uso: @%s cofrinho <capacidade> <por_usuário>"""
|
||||
inlineResultTipjarTitle = """🍯 Criar um cofrinho de %d sat."""
|
||||
inlineResultTipjarDescription = """👉 Clique aqui para criar um cofrinho neste chat."""
|
||||
|
||||
inlineTipjarMessage = """Pressione 💸 para *pagar %d sat* a esse cofrinho de %s.
|
||||
|
||||
🙏 Doados: *%d*/%d sat (por %d usuários)
|
||||
%s"""
|
||||
inlineTipjarEndedMessage = """🍯 O cofrinho de %s está cheio ⭐️\n\n🏅 %d sat doados por %d usuários."""
|
||||
inlineTipjarAppendMemo = """\n✉️ %s"""
|
||||
inlineTipjarCancelledMessage = """🚫 Cofrinho cancelado."""
|
||||
inlineTipjarInvalidPeruserAmountMessage = """🚫 Quantidade por usuário não divisor da capacidade."""
|
||||
inlineTipjarInvalidAmountMessage = """🚫 Quantia inválida."""
|
||||
inlineTipjarSentMessage = """🍯 %d sat enviado(s) a %s."""
|
||||
inlineTipjarReceivedMessage = """🍯 %s lhe enviou %d sat."""
|
||||
inlineTipjarHelpTipjarInGroup = """Criar uma cofrinho em grupo com o bot dentro ou usar o 👉 comando_inline_ (/advanced para mais)."""
|
||||
inlineTipjarHelpText = """📖 Opa, isso não funcionou. %s
|
||||
|
||||
*Uso:* `/tipjar <capacidade> <por_usuário>`
|
||||
*Exemplo:* `/tipjar 210 21`"""
|
||||
@@ -1,340 +0,0 @@
|
||||
# COMMANDS
|
||||
|
||||
helpCommandStr = """справка"""
|
||||
basicsCommandStr = """основы"""
|
||||
tipCommandStr = """tip"""
|
||||
balanceCommandStr = """баланс"""
|
||||
sendCommandStr = """отправить"""
|
||||
invoiceCommandStr = """инвойс"""
|
||||
payCommandStr = """оплатить"""
|
||||
donateCommandStr = """пожертвовать"""
|
||||
advancedCommandStr = """детально"""
|
||||
transactionsCommandStr = """транзакции"""
|
||||
logCommandStr = """лог"""
|
||||
listCommandStr = """список"""
|
||||
|
||||
linkCommandStr = """link"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """faucet"""
|
||||
|
||||
tipjarCommandStr = """tipjar"""
|
||||
receiveCommandStr = """получить"""
|
||||
hideCommandStr = """спрятать"""
|
||||
volcanoCommandStr = """volcano"""
|
||||
showCommandStr = """показать"""
|
||||
optionsCommandStr = """опции"""
|
||||
settingsCommandStr = """настройки"""
|
||||
saveCommandStr = """сохранить"""
|
||||
deleteCommandStr = """удалить"""
|
||||
infoCommandStr = """инфо"""
|
||||
|
||||
# NOTIFICATIONS
|
||||
|
||||
cantDoThatMessage = """Вы не можете это сделать."""
|
||||
cantClickMessage = """Вы не можете нажать на эту кнопку."""
|
||||
balanceTooLowMessage = """Недостаточно средств."""
|
||||
|
||||
# BUTTONS
|
||||
|
||||
sendButtonMessage = """✅ Отправить"""
|
||||
payButtonMessage = """✅ Оплатить"""
|
||||
payReceiveButtonMessage = """💸 Оплатить"""
|
||||
receiveButtonMessage = """✅ Получить"""
|
||||
withdrawButtonMessage = """✅ Вывести"""
|
||||
cancelButtonMessage = """🚫 Отмена"""
|
||||
collectButtonMessage = """✅ Забрать"""
|
||||
nextButtonMessage = """Вперед"""
|
||||
backButtonMessage = """Назад"""
|
||||
acceptButtonMessage = """Принять"""
|
||||
denyButtonMessage = """Запретить"""
|
||||
tipButtonMessage = """Tip"""
|
||||
revealButtonMessage = """Развернуть"""
|
||||
showButtonMessage = """Показать"""
|
||||
hideButtonMessage = """Спрятать"""
|
||||
joinButtonMessage = """Присоединиться"""
|
||||
optionsButtonMessage = """Опции"""
|
||||
settingsButtonMessage = """Настройки"""
|
||||
saveButtonMessage = """Сохранить"""
|
||||
deleteButtonMessage = """Удалить"""
|
||||
infoButtonMessage = """Инфо"""
|
||||
|
||||
cancelButtonEmoji = """🚫"""
|
||||
payButtonEmoji = """💸"""
|
||||
|
||||
# HELP
|
||||
|
||||
helpMessage = """⚡️ *Wallet*
|
||||
_Этот бот представляет собой кошелек Bitcoin Lightning, который может отправлять Tip (небольшие сумму в Сатоши) через Telegram. Чтобы отправить Tip, добавьте бота в групповой чат. Основной единицей чаевых являются сатоши (sat). 100 000 000 сат = 1 биткоин. Введите 📚 /basics для получения дополнительной информации._
|
||||
|
||||
❤️ *Donate*
|
||||
_Этот бот не взимает комиссии, но его работа обходится в сатоши. Если вам нравится бот, пожалуйста, поддержите этот проект пожертвованием. Чтобы сделать пожертвование, воспользуйтесь командой_ `/donate 1000`
|
||||
|
||||
%s
|
||||
|
||||
⚙️ *Команды*
|
||||
*/tip* 🏅 Ответьте на сообщение чтобы отправить Tip (небольшую сумму в Сатоши): `/tip <amount> [<memo>]`
|
||||
*/balance* 👑 Проверить баланс: `/balance`
|
||||
*/send* 💸 Отправить ссредства пользователю: `/send <количество> @<user> или <user>@ln.tips [<memo>]`
|
||||
*/invoice* ⚡️ Получить через Lightning: `/invoice <количество> [<memo>]`
|
||||
*/pay* ⚡️ Оплатить через Lightning: `/pay <инвойс>`
|
||||
*/donate* ❤️ Отправить пожертвование проекту: `/donate 1000`
|
||||
*/advanced* 🤖 Продвинутые возможности.
|
||||
*/help* 📖 Прочитайте справку."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Info*"""
|
||||
infoYourLightningAddress = """Ваш адрес в системе Lightning - `%s`"""
|
||||
|
||||
basicsMessage = """🧡 *Биткоин*
|
||||
_Биткоин - это валюта интернета. Она не имеет ограничений и децентрализована, у нее нет хозяев и контролирующих органов. Биткойн - это разумные деньги, которые быстрее, надежнее и всеохватнее, чем традиционная финансовая система._
|
||||
|
||||
🧮 *Экономика*
|
||||
_Наименьшей единицей Биткоина являются "Сатоши" (sat), а 100 000 000 sat = 1 Биткойн. В мире существует только 21 миллион биткоинов. Стоимость Биткойна выражаемая в фиатной валюте может меняться ежедневно. Однако, если вы живете по стандарту Биткойна, то 1 sat всегда будет равен 1 sat._
|
||||
|
||||
⚡️ *The Lightning Network*
|
||||
_The Lightning Network - это платежный протокол, который обеспечивает быстрые и дешевые платежи Биткоинами, практически не требующие энергии. Именно благодаря ему Биткоин доступен миллиардам людей по всему миру._
|
||||
|
||||
📲 *Lightning-кошельки*
|
||||
_Ваши средства на этом боте могут быть отправлены на любой другой Lightning-кошелек и наоборот. Рекомендуемые Lightning-кошельки для вашего телефона:_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (не требующие обслуживания), или_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(простой)_.
|
||||
|
||||
📄 *Open Source*
|
||||
_Этот бот является бесплатным и_ [с открытым исходным кодом](https://github.com/LightningTipBot/LightningTipBot) _. Вы можете запустить его на своем компьютере и использовать в своем сообществе._
|
||||
|
||||
✈️ *Telegram*
|
||||
_Добавьте этого бота в чат вашей группы Telegram для /tip сообщений. Если вы сделаете бота администратором группы, он также будет очищать команды для поддержания чистоты в чате._
|
||||
|
||||
🏛 *Условия*
|
||||
_Мы не являемся хранителями ваших средств. Мы будем действовать в ваших интересах, но мы также понимаем, что ситуация без поддержки стандарта KYC - немного сложная, до тех пор, пока мы не придумаем что-нибудь. Любая сумма, которую вы загрузите на свой кошелек, будет считаться пожертвованием. Не отдавайте нам все свои деньги. Имейте в виду, что этот бот находится в стадии бета-разработки. Используйте на свой страх и риск._
|
||||
|
||||
❤️ *Пожертвования*
|
||||
_Этот бот не взимает комиссии, но его работа обходится в сатоши. Если вам нравится бот, пожалуйста, поддержите этот проект пожертвованием. Чтобы сделать пожертвование, воспользуйтесь командой_ `/donate 1000`"""
|
||||
|
||||
helpNoUsernameMessage = """👋 Пожалуйста, установите имя пользователя в Telegram."""
|
||||
|
||||
advancedMessage = """%s
|
||||
|
||||
👉 *Команды*
|
||||
*send* 💸 Отправить Сатоши в чате: `%s send <количество> [<user>] [<memo>]`
|
||||
*receive* 🏅 Запросить оплату: `... receive <количество> [<user>] [<memo>]`
|
||||
*faucet* 🚰 Создать криптораздачу: `... faucet <ёмкость> <на_пользователя> [<memo>]`
|
||||
*tipjar* 🍯 Создать копилку: `... tipjar <ёмкость> <на_пользователя> [<memo>]`
|
||||
|
||||
📖 Вы можете использовать команды в любом чате, даже в личных беседах. Подождите секунду после ввода команды и *щелкните* результат, не нажимайте Enter..
|
||||
|
||||
⚙️ *Продвинутые команды*
|
||||
*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)
|
||||
*/lnurl* Получить или оплатить через ⚡️Lnurl: `/lnurl` or `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Создать криптораздачу: `/faucet <ёмкость> <на_пользователя>`
|
||||
*/tipjar* 🍯 Создать копилку: `/tipjar <ёмкость> <на_пользователя>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 Введите количество между %d и %d sat."""
|
||||
enterAmountMessage = """💯 Введите количество."""
|
||||
enterUserMessage = """👤 введите пользователя."""
|
||||
errorReasonMessage = """🚫 Ошибка: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Настраиваю кошелёк для вас..."""
|
||||
startWalletCreatedMessage = """🧮 Кошелёк создан."""
|
||||
startWalletReadyMessage = """✅ *Кошелёк готов к использованию.*"""
|
||||
startWalletErrorMessage = """🚫 Ошибка инициализации кошелька. Попробуйте позже."""
|
||||
startNoUsernameMessage = """☝️ Похоже, что у вас еще нет @имени_пользователя в Telegram. Это нормально, оно не обязательно для использования этого бота. Однако, чтобы лучше использовать свой кошелек, установите имя пользователя в настройках Telegram. Затем введите /balance, чтобы бот мог обновить свои данные о вас."""
|
||||
|
||||
# BALANCE
|
||||
|
||||
balanceMessage = """👑 *Ваш баланс:* %d sat"""
|
||||
balanceErrorMessage = """🚫 Не удалось получить ваш баланс. Пожалуйста, повторите попытку позже."""
|
||||
|
||||
# TIP
|
||||
|
||||
tipDidYouReplyMessage = """Вы ответили на сообщение чтобы отправить Сатоши? Чтобы ответить на любое сообщение, нажмите правой кнопкой мыши -> Ответить на компьютере или проведите пальцем по сообщению на телефоне. Если вы хотите отправить Сатоши непосредственно другому пользователю, используйте команду /send."""
|
||||
tipInviteGroupMessage = """ℹ️ Кстати, вы можете пригласить этого бота в любую группу, чтобы можно было отправлять чаевые там."""
|
||||
tipEnterAmountMessage = """Ввели ли вы сумму?"""
|
||||
tipValidAmountMessage = """Ввели ли вы правильную сумму?"""
|
||||
tipYourselfMessage = """📖 Вы не можете отправлять самому себе."""
|
||||
tipSentMessage = """💸 %d sat отправлено %s."""
|
||||
tipReceivedMessage = """🏅 %s отправил(а) вам %d sat."""
|
||||
tipErrorMessage = """🚫 Отправка не удалась."""
|
||||
tipUndefinedErrorMsg = """пожалуйста попробуйте позжа."""
|
||||
tipHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/tip <количество> [<memo>]`
|
||||
*Пример:* `/tip 1000 Спасибо!`"""
|
||||
|
||||
# SEND
|
||||
|
||||
sendValidAmountMessage = """Ввели ли вы правильную сумму?"""
|
||||
sendUserHasNoWalletMessage = """🚫 Пользователь %s не создал кошелёк."""
|
||||
sendSentMessage = """💸 %d sat отправлено %s."""
|
||||
sendPublicSentMessage = """💸 %d sat отправил(а) %s для %s."""
|
||||
sendReceivedMessage = """🏅 %s отправил(а) вам %d sat."""
|
||||
sendErrorMessage = """🚫 Неуспешная отправка."""
|
||||
confirmSendMessage = """Вы хотите отправить Сатоши %s?\n\n💸 Amount: %d sat"""
|
||||
confirmSendAppendMemo = """\n✉️ %s"""
|
||||
sendCancelledMessage = """🚫 Отправка отменена."""
|
||||
errorTryLaterMessage = """🚫 Ошибка. Пожалуйста попробуйте позже."""
|
||||
sendSyntaxErrorMessage = """Вы ввели сумму и получателя? Вы можете использовать команду /send для отправки либо пользователям Telegram, например %s, либо на адрес Lightning, например LightningTipBot@ln.tips."""
|
||||
sendHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/send <количество> <пользователь> [<memo>]`
|
||||
*Пример:* `/send 1000 @LightningTipBot I just like the bot ❤️`
|
||||
*Пример:* `/send 1234 LightningTipBot@ln.tips`"""
|
||||
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ Вы получили %d sat."""
|
||||
invoiceEnterAmountMessage = """Ввели ли вы сумму?"""
|
||||
invoiceValidAmountMessage = """Ввели ли вы правильную сумму?"""
|
||||
invoiceHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/invoice <количество> [<memo>]`
|
||||
*Пример:* `/invoice 1000 Спасибо!`"""
|
||||
|
||||
# PAY
|
||||
|
||||
paymentCancelledMessage = """🚫 Платёж отменён."""
|
||||
invoicePaidMessage = """⚡️ Платёж отправлен."""
|
||||
invoicePublicPaidMessage = """⚡️ %s отправил(а) платёж."""
|
||||
invalidInvoiceHelpMessage = """Вы ввели существующий счет в Lightning? Попробуйте /send, если вы хотите отправить пользователю Telegram или по адресу Lightning."""
|
||||
invoiceNoAmountMessage = """🚫 Невозможно оплатить инвойс без указания суммы."""
|
||||
insufficientFundsMessage = """🚫 Недостаточно средств. У вас есть %d sat, но вам нужно не менее %d sat."""
|
||||
feeReserveMessage = """⚠️ Отправка всего вашего баланса может провалиться из-за сетевых сборов. Если это не удается, попробуйте отправить немного меньше."""
|
||||
invoicePaymentFailedMessage = """🚫 Платёж не прошёл: %s"""
|
||||
invoiceUndefinedErrorMessage = """Невозможно оплатить счёт."""
|
||||
confirmPayInvoiceMessage = """Хотите ли вы отправить этот платеж?\n\n💸 Amount: %d sat"""
|
||||
confirmPayAppendMemo = """\n✉️ %s"""
|
||||
payHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/pay <инвойс>`
|
||||
*Пример:* `/pay lnbc20n1psscehd...`"""
|
||||
|
||||
# DONATE
|
||||
|
||||
donationSuccess = """🙏 Спасибо за ваше пожертвование."""
|
||||
donationErrorMessage = """🚫 О нет! Пожертвование не удалось."""
|
||||
donationProgressMessage = """🧮 Подготовка вашего пожертвования..."""
|
||||
donationFailedMessage = """🚫 Пожертвование не удалось: %s"""
|
||||
donateEnterAmountMessage = """Ввели ли вы сумму?"""
|
||||
donateValidAmountMessage = """Ввели ли вы правильную сумму?"""
|
||||
donateHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/donate <количество>`
|
||||
*Пример:* `/donate 1000`"""
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 Не удалось распознать счет Lightning или LNURL. Попробуйте отцентрировать QR-код, обрезать фотографию или увеличить масштаб."""
|
||||
photoQrRecognizedMessage = """✅ QR код:
|
||||
`%s`"""
|
||||
|
||||
# LNURL
|
||||
|
||||
lnurlReceiveInfoText = """👇 Вы можете использовать этот статический LNURL для приема платежей."""
|
||||
lnurlResolvingUrlMessage = """🧮 Уточнение адреса..."""
|
||||
lnurlGettingUserMessage = """🧮 Подготовка платежа..."""
|
||||
lnurlPaymentFailed = """🚫 Платеж не прошел: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Неверная сумма."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Сумма должна быть от %d до %d sat."""
|
||||
lnurlNoUsernameMessage = """🚫 Вам нужно установить имя пользователя Telegram для получения платежей через LNURL."""
|
||||
lnurlHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/lnurl [количество] <lnurl>`
|
||||
*Пример:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LNURL WITHDRAW
|
||||
|
||||
confirmLnurlWithdrawMessage = """Вы хотите вывести средства?\n\n💸 Сумма: %d сб"""
|
||||
lnurlPreparingWithdraw = """🧮 Подготовка к выводу средств..."""
|
||||
lnurlWithdrawFailed = """🚫 Вывод средств не удался."""
|
||||
lnurlWithdrawCancelled = """🚫 Вывод средств отменен."""
|
||||
lnurlWithdrawSuccess = """✅ Вывод средств запрошен."""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Подключение кошелька*
|
||||
|
||||
⚠️ Никогда и никому не сообщайте URL или QR-код, иначе они смогут получить доступ к вашим средствам.
|
||||
|
||||
- *BlueWallet:* Нажмите *New wallet*, *Import wallet*, *Scan or import a file*, и отсканируйте QR-код.
|
||||
- *Zeus:* Скопируйте URL ниже, нажмите *Add a new node*, *Import* (the URL), *Save Node Config*."""
|
||||
couldNotLinkMessage = """🚫 Не удалось связать ваш кошелек. Пожалуйста, повторите попытку позже."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
inlineQueryFaucetTitle = """🚰 Создать криптораздачу."""
|
||||
inlineQueryFaucetDescription = """Использование: @%s faucet <capacity> <per_user>"""
|
||||
inlineResultFaucetTitle = """🚰 Создать %d sat криптораздачу."""
|
||||
inlineResultFaucetDescription = """👉 Нажмите здесь, чтобы создать криптораздачу в этом чате."""
|
||||
|
||||
inlineFaucetMessage = """Нажмите ✅, чтобы забрать %d sat из этой криптораздачи.
|
||||
|
||||
🚰 Осталось: %d/%d sat (отдано %d/%d пользователям)
|
||||
%s"""
|
||||
inlineFaucetEndedMessage = """🚰 Криптораздача завершена 🍺\n\n🏅 %d sat отдано %d пользователям."""
|
||||
inlineFaucetAppendMemo = """\n✉️ %s"""
|
||||
inlineFaucetCreateWalletMessage = """Напишите %s 👈 чтобы управлять своим кошельком."""
|
||||
inlineFaucetCancelledMessage = """🚫 Криптораздача отменена."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 Количество пользователей не является делителем емкости."""
|
||||
inlineFaucetInvalidAmountMessage = """🚫 Неверное количество."""
|
||||
inlineFaucetSentMessage = """🚰 %d sat отправлено %s."""
|
||||
inlineFaucetReceivedMessage = """🚰 %s отправил вам %d sat."""
|
||||
inlineFaucetHelpFaucetInGroup = """Создайте криптораздачу в группе с ботом внутри или используйте 👉 команду (/advanced для справки)."""
|
||||
inlineFaucetHelpText = """📖 Упс, это не сработало. %s
|
||||
|
||||
*Использование:* `/faucet <ёмкость> <на_пользователя>`
|
||||
*Пример:* `/faucet 210 21`"""
|
||||
|
||||
# INLINE SEND
|
||||
|
||||
inlineQuerySendTitle = """💸 Отправьте платеж в чат."""
|
||||
inlineQuerySendDescription = """Использование: @%s send <количество> [<пользователь>] [<memo>]"""
|
||||
inlineResultSendTitle = """💸 Отправить %d sat."""
|
||||
inlineResultSendDescription = """👉 Нажмите, чтобы отправить %d сат в этот чат."""
|
||||
|
||||
inlineSendMessage = """Нажмите ✅ для получения платежа от %s.\n\n💸 Сумма: %d sat"""
|
||||
inlineSendAppendMemo = """\n✉️ %s"""
|
||||
inlineSendUpdateMessageAccept = """💸 %d sat отправлено с %s на %s."""
|
||||
inlineSendCreateWalletMessage = """Напишите %s 👈 чтобы управлять своим кошельком."""
|
||||
sendYourselfMessage = """📖 Вы не можете платить себе."""
|
||||
inlineSendFailedMessage = """🚫 Отправка не удалась."""
|
||||
inlineSendInvalidAmountMessage = """🚫 Сумма должна быть больше 0."""
|
||||
inlineSendBalanceLowMessage = """🚫 Ваш баланс слишком низкий."""
|
||||
|
||||
# INLINE RECEIVE
|
||||
|
||||
inlineQueryReceiveTitle = """🏅 Запросить платёж в чате."""
|
||||
inlineQueryReceiveDescription = """Использование: @%s receive <количество> [<пользователь>] [<memo>]"""
|
||||
inlineResultReceiveTitle = """🏅 Получить %d sat."""
|
||||
inlineResultReceiveDescription = """👉 Нажмите, чтобы запросить выплату в размере %d sat."""
|
||||
|
||||
inlineReceiveMessage = """Нажмите 💸 чтобы отправить Сатоши %s.\n\n💸 Количество: %d sat"""
|
||||
inlineReceiveAppendMemo = """\n✉️ %s"""
|
||||
inlineReceiveUpdateMessageAccept = """💸 %d sat отправлено от %s, получатель - %s."""
|
||||
inlineReceiveCreateWalletMessage = """Напишите %s 👈 чтобы управлять своим кошельком."""
|
||||
inlineReceiveYourselfMessage = """📖 Вы не можете платить себе."""
|
||||
inlineReceiveFailedMessage = """🚫 Получение не удалось."""
|
||||
inlineReceiveCancelledMessage = """🚫 Получение отменено."""
|
||||
|
||||
# TIPJAR
|
||||
|
||||
inlineQueryTipjarTitle = """🍯 Создать копилку."""
|
||||
inlineQueryTipjarDescription = """Использование: @%s tipjar <ёмкость> <на_пользователя>"""
|
||||
inlineResultTipjarTitle = """🍯 Создать копилку на %d sat ."""
|
||||
inlineResultTipjarDescription = """👉 Нажмите здесь, чтобы создать копилку в этом чате."""
|
||||
|
||||
inlineTipjarMessage = """Нажмите 💸 чтобы *отправить %d sat* в эту копилку, созданную %s.
|
||||
|
||||
🙏 Накоплено: *%d*/%d sat (от %d пользователей)
|
||||
%s"""
|
||||
inlineTipjarEndedMessage = """🍯 %s's копилка заполнена ⭐️\n\n🏅 %d sat отправи(л/ли) %d пользовате(ль/ли)."""
|
||||
inlineTipjarAppendMemo = """\n✉️ %s"""
|
||||
inlineTipjarCancelledMessage = """🚫 Копилка отозвана."""
|
||||
inlineTipjarInvalidPeruserAmountMessage = """🚫 Количество пользователей не является делителем емкости."""
|
||||
inlineTipjarInvalidAmountMessage = """🚫 Отправка не удалась."""
|
||||
inlineTipjarSentMessage = """🍯 %d sat отправлено в пользу %s."""
|
||||
inlineTipjarReceivedMessage = """🍯 %s отправил вам %d sat."""
|
||||
inlineTipjarHelpTipjarInGroup = """Создайте копилку в группе с ботом внутри или используйте 👉 команду (/advanced для справки)."""
|
||||
inlineTipjarHelpText = """📖 Oops, that didn't work. %s
|
||||
|
||||
*Использование:* `/tipjar <ёмкость> <на_пользователя>`
|
||||
*Пример:* `/tipjar 210 21`"""
|
||||
@@ -1,304 +0,0 @@
|
||||
# COMMANDS
|
||||
|
||||
helpCommandStr = """yardım"""
|
||||
basicsCommandStr = """temelbilgi"""
|
||||
tipCommandStr = """bahşiş"""
|
||||
balanceCommandStr = """kredi"""
|
||||
sendCommandStr = """gönder"""
|
||||
invoiceCommandStr = """fatura"""
|
||||
payCommandStr = """öde"""
|
||||
donateCommandStr = """bağış"""
|
||||
advancedCommandStr = """gelişmiş"""
|
||||
transactionsCommandStr = """işlemler"""
|
||||
logCommandStr = """kayıt"""
|
||||
listCommandStr = """liste"""
|
||||
|
||||
linkCommandStr = """bağlan"""
|
||||
lnurlCommandStr = """lnurl"""
|
||||
faucetCommandStr = """fıçı"""
|
||||
|
||||
tipjarCommandStr = """bağışkutusu"""
|
||||
receiveCommandStr = """iste"""
|
||||
hideCommandStr = """sakla"""
|
||||
volcanoCommandStr = """volkan"""
|
||||
showCommandStr = """göster"""
|
||||
optionsCommandStr = """seçenekler"""
|
||||
settingsCommandStr = """ayarlar"""
|
||||
saveCommandStr = """kaydet"""
|
||||
deleteCommandStr = """sil"""
|
||||
infoCommandStr = """info"""
|
||||
|
||||
# NOTIFICATIONS
|
||||
|
||||
cantDoThatMessage = """Bunu yapamazsın."""
|
||||
cantClickMessage = """Bu butona basamazsın."""
|
||||
balanceTooLowMessage = """Kredin yetersiz."""
|
||||
|
||||
# BUTTONS
|
||||
|
||||
sendButtonMessage = """✅ Gönder"""
|
||||
payButtonMessage = """✅ Öde"""
|
||||
payReceiveButtonMessage = """💸 Öde"""
|
||||
receiveButtonMessage = """✅ İste"""
|
||||
cancelButtonMessage = """🚫 İptal"""
|
||||
collectButtonMessage = """✅ Topla"""
|
||||
nextButtonMessage = """İleri"""
|
||||
backButtonMessage = """Geri"""
|
||||
acceptButtonMessage = """Onayla"""
|
||||
denyButtonMessage = """Reddet"""
|
||||
tipButtonMessage = """Bahşiş"""
|
||||
revealButtonMessage = """Göster"""
|
||||
showButtonMessage = """Göster"""
|
||||
hideButtonMessage = """Sakla"""
|
||||
joinButtonMessage = """Katıl"""
|
||||
optionsButtonMessage = """Seçenekler"""
|
||||
settingsButtonMessage = """Ayarlar"""
|
||||
saveButtonMessage = """Kaydet"""
|
||||
deleteButtonMessage = """Sil"""
|
||||
infoButtonMessage = """Info"""
|
||||
|
||||
# HELP
|
||||
|
||||
helpMessage = """⚡️ *Cüzdan*
|
||||
_Bitcoin Lightning Cüzdan botu ile Telegram üzerinden bahşiş gönderebilirsin. Bahşiş göndermek için botu bir grup sohbetine ekle. Temel bahşiş birimi Satoshi’dir (sat). 100,000,000 sat = 1 Bitcoin. Daha fazla bilgi için 📚 /basics gir._
|
||||
|
||||
❤️ *Bağış yap*
|
||||
_Bu bot ücretsizdir, ancak çalıştırılması için Satoshi gerekir. Botu beğendiysen bağış yaparak projeye destek olabilirsin. Bağış yapmak için şunu gir: _ `/donate 1000`
|
||||
|
||||
%s
|
||||
|
||||
⚙️ *Komutlar*
|
||||
*/tip* 🏅 Bağış yapmak için mesajı cevapla: `/tip <miktar> [<bildirim>]`
|
||||
*/balance* 👑 Kredini sorgula: `/balance`
|
||||
*/send* 💸 Bir kullanıcıya gönder: `/send <miktar> @user veya user@ln.tips [<bildirim>]`
|
||||
*/invoice* ⚡️ Lightning ile iste: `/invoice <miktar> [<bildirim>]`
|
||||
*/pay* ⚡️ Lightning ile öde: `/pay <invoice>`
|
||||
*/donate* ❤️ Projeye bağış yap: `/donate 1000`
|
||||
*/advanced* 🤖 Gelişmiş fonksiyonlar.
|
||||
*/help* 📖 Yardım."""
|
||||
|
||||
infoHelpMessage = """ℹ️ *Info*"""
|
||||
infoYourLightningAddress = """Lightning adresin `%s`"""
|
||||
|
||||
basicsMessage = """🧡 *Bitcoin*
|
||||
_Bitcoin internetin para birimidir. Herkese açık, merkezi olmayan, kontrol edeni olmayan, klasik finansal sistemden daha hızlı, daha güvenli ve daha adil olan sağlam bir paradır._
|
||||
|
||||
🧮 *Ekonomi*
|
||||
_En küçük Bitcoin birimi Satoshi’dir (sat). 100.000.000 sat = 1 Bitcoin. Asla 21 milyondan fazla Bitcoin üretilmeyecek. Bitcoin'in itibari para değeri günlük olarak değişebilir. Ancak Bitcoin Standardı kullanıyorsan, 1 sat sonsuza kadar 1 sat değerinde olacaktır._
|
||||
|
||||
⚡️ *Lightning Network*
|
||||
_Lightning Network neredeyse hiç enerji gerektirmeyen hızlı ve ucuz Bitcoin ödemelerine izin veren bir protokolüdür. Böylece Bitcoin dünya çapında milyarlarca insana ulaşır._
|
||||
|
||||
📲 *Lightning Cüzdanlar*
|
||||
_Bu bottaki paranı dünyadaki herhangi bir Lightning cüzdanına gönderebilirsin. Cep telefonunun için önerilen Lightning cüzdanları şunlardır:_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (emanet edilmeyen), veya_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(kolay)_.
|
||||
|
||||
📄 *Açık Kaynak*
|
||||
_Bu bot ücretsiz ve_ [açık kaynak](https://github.com/LightningTipBot/LightningTipBot) _yazılım. Kendi bilgisayarında çalıştırabilir ve topluluğun için kullanabilirsin._
|
||||
|
||||
✈️ *Telegram*
|
||||
_/tip göndermek için botu Telegram grubunuza ekle. Bot grubun yöneticisiyse, yürütmeden sonra bazı komutları silerek sohbeti de temizleyecektir._
|
||||
|
||||
🏛 *Kullanım Şartları*
|
||||
_Biz senin paranın emanetçisi değiliz. Senin faydanı gözetiyoruz. Ancak KYC'siz durumun biraz karmaşık olduğunun da farkındayız. Başka bir çözüm bulana kadar bu bottaki tüm tutarları bağış olarak kabul ediyoruz. Tüm paranı bize verme. Bu botun hala beta aşamasında olduğunu unutma. Kullanımın senin sorumluluğundadır._
|
||||
|
||||
❤️ *Bağış yap*
|
||||
_Bu bot ücretsizdir, ancak çalıştırılması için Satoshi gerekir. Botu beğendiysen bağış yaparak projeye destek olabilirsin. Bağış yapmak için şunu gir:_ `/donate 1000`"""
|
||||
|
||||
helpNoUsernameMessage = """👋 Ayarlarda bir Telegram kullanıcı adı seç."""
|
||||
|
||||
advancedMessage = """%s
|
||||
|
||||
👉 *Inline komutlar*
|
||||
*send* 💸 Bir sohbete sat gönder: `%s send <miktar> [<kullanıcı>] [<bildirim>]`
|
||||
*receive* 🏅 Ödeme iste: `%s receive <miktar> [<kullanıcı>] [<bildirim>]`
|
||||
*faucet* 🚰 Bir fıçı oluştur: `%s faucet <toplam> <kullanıcı_başına> [<bildirim>]`
|
||||
*tipjar* 🍯 Bir tipjar oluştur: `... tipjar <toplam> <kullanıcı_başına> [<bildirim>]`
|
||||
|
||||
📖 İnline komutları her sohbette ve hatta özel mesajlarda kullanabilirsin. Komutu yazdıktan sonra bir saniye bekle ve Enter yazmak yerine sonuca *tıkla*.
|
||||
|
||||
⚙️ *Gelişmiş komutlar*
|
||||
*/link* 🔗 Cüzdanını bağla: [BlueWallet](https://bluewallet.io/) veya [Zeus](https://zeusln.app/)
|
||||
*/lnurl* ⚡️ Lnurl iste veya gönder: `/lnurl` veya `/lnurl <lnurl>`
|
||||
*/faucet* 🚰 Bir fıçı oluştur: `/faucet <toplam> <kullanıcı_başına>`
|
||||
*/tipjar* 🍯 Bir tipjar oluştur: `/tipjar <capacity> <per_user>`"""
|
||||
|
||||
# GENERIC
|
||||
enterAmountRangeMessage = """💯 %d ve %d sat arasında bir miktar gir."""
|
||||
enterAmountMessage = """💯 Bir miktar gir."""
|
||||
enterUserMessage = """👤 Bir kullanıcı gir."""
|
||||
errorReasonMessage = """🚫 Hata: %s"""
|
||||
|
||||
# START
|
||||
|
||||
startSettingWalletMessage = """🧮 Cüzdanın hazırlanıyor…"""
|
||||
startWalletCreatedMessage = """🧮 Cüzdanın hazır."""
|
||||
startWalletReadyMessage = """✅ *Cüzdanın hazır.*"""
|
||||
startWalletErrorMessage = """🚫 Cüzdanın hazırlanırken bir hata oluştu. Lütfen daha sonra tekrar dene."""
|
||||
startNoUsernameMessage = """☝️ Henüz bir Telegram kullanıcı @adın yok gibi görünüyor. Sorun değil, bu botu kullanmak için kullanıcı adına ihtiyacın yok. Ancak tüm fonksiyonları kullanabilmek için Telegram ayarlarında bir kullanıcı adı belirlemelisin. Ardından botun seninle ilgili bilgilerini güncelleyebilmesi için bir kez /balance gir."""
|
||||
|
||||
# BALANCE
|
||||
|
||||
balanceMessage = """👑 *Kredin:* %d sat"""
|
||||
balanceErrorMessage = """🚫 Şu an kredini okuyamıyorum. Lütfen daha sonra tekrar dene."""
|
||||
|
||||
# TIP
|
||||
|
||||
tipDidYouReplyMessage = """Birine bahşiş göndermek için bir mesajı yanıtladın mı? Yanıtlamak için bilgisayarında mesaja sağ tıklayarak Yanıtla. Telefonda ise mesajı kaydır. Ödemeyi doğrudan başka bir kullanıcıya göndermek istiyorsan /send komutunu kullan."""
|
||||
tipInviteGroupMessage = """ℹ️ Bu arada, bu botu herhangi bir grup sohbetine davet edebilir ve orada bahşiş dağıtabilirsin."""
|
||||
tipEnterAmountMessage = """Miktar girdin mi?"""
|
||||
tipValidAmountMessage = """Geçerli bir miktar girdin mi?"""
|
||||
tipYourselfMessage = """📖 Kendi kendine bahşiş gönderemezsin."""
|
||||
tipSentMessage = """💸 %d sat %s a gönderildi."""
|
||||
tipReceivedMessage = """🏅 %s sana %d sat bahşiş gönderdi."""
|
||||
tipErrorMessage = """🚫 Bahşiş gönderilemedi."""
|
||||
tipUndefinedErrorMsg = """lütfen daha sonra tekrar dene."""
|
||||
tipHelpText = """📖 Hoppalaa… olmadı. %s
|
||||
|
||||
*Komut:* `/tip <miktar> [<bildirim>]`
|
||||
*Örnek:* `/tip 1000 Çok iyi yaa!`"""
|
||||
|
||||
# SEND
|
||||
|
||||
sendValidAmountMessage = """Geçerli bir miktar girdin mi?"""
|
||||
sendUserHasNoWalletMessage = """🚫 %s henüz bir cüzdan oluşturmadı."""
|
||||
sendSentMessage = """💸 %d sat %s a gönderildi."""
|
||||
sendPublicSentMessage = """💸 %d sat %s dan %s a gönderildi."""
|
||||
sendReceivedMessage = """🏅 %s sana %d sat gönderdi."""
|
||||
sendErrorMessage = """🚫 Gönderim başarılı olmadı."""
|
||||
confirmSendMessage = """%s a ödeme göndermek istiyor musun?\n\n💸 Miktar: %d sat"""
|
||||
confirmSendAppendMemo = """\n✉️ %s"""
|
||||
sendCancelledMessage = """🚫 Gönderim iptal edildi."""
|
||||
errorTryLaterMessage = """🚫 Hata. Lütfen daha sonra tekrar dene."""
|
||||
sendSyntaxErrorMessage = """Geçerli bir miktar ve kullanıcı girdin mi? /send komutu ile bir Telegram kullanıcısına, örnek %s, veya bir Lightning adrese, örnek LightningTipBot@ln.tips, gönderilebilir."""
|
||||
sendHelpText = """📖 Hoppalaa… olmadı. %s
|
||||
|
||||
*Komut:* `/send <miktar> <kullanıcı> [<bildirim>]`
|
||||
*Örnek:* `/send 1000 @LightningTipBot Bot harika kanka! ❤️`
|
||||
*Örnek:* `/send 1234 LightningTipBot@ln.tips`"""
|
||||
|
||||
# INVOICE
|
||||
|
||||
invoiceReceivedMessage = """⚡️ %d sat sana geldi."""
|
||||
invoiceEnterAmountMessage = """Miktar girdin mi?"""
|
||||
invoiceValidAmountMessage = """Geçerli bir miktar girdin mi?"""
|
||||
invoiceHelpText = """📖 Hoppalaa… olmadı. %s
|
||||
|
||||
*Komut:* `/invoice <miktar> [<bildirim>]`
|
||||
*Örnek:* `/invoice 1000 Şimdiden teşekkürler!`"""
|
||||
|
||||
# PAY
|
||||
|
||||
paymentCancelledMessage = """🚫 Ödeme iptal edildi."""
|
||||
invoicePaidMessage = """⚡️ Ödeme gönderildi."""
|
||||
invoicePublicPaidMessage = """⚡️ %s ödeme gönderdi."""
|
||||
invalidInvoiceHelpMessage = """Geçerli bir Lightning Invoice girdin mi? Telegram kullanıcısına veya Lightning adrese ödeme yapmak için /send komutunu kullan."""
|
||||
invoiceNoAmountMessage = """🚫 Miktar belirtilmemiş Invoice ödenemez."""
|
||||
insufficientFundsMessage = """🚫 Kredin yetersiz. Şu an cüzdanında %d sat var. Ancak en az %d sat gerekiyor."""
|
||||
feeReserveMessage = """⚠️ Cüzdanındaki tüm miktarı göndermek istiyorsun. Ancak Lightning ücreti ödenemeyeceği için gönderim başarısız olabilir. Bu durumda daha az bir miktar dene."""
|
||||
invoicePaymentFailedMessage = """🚫 Ödeme başarısız: %s"""
|
||||
invoiceUndefinedErrorMessage = """Invoice ödenemedi."""
|
||||
confirmPayInvoiceMessage = """Bu ödemeyi göndermek istiyor musun?\n\n💸 Miktar: %d sat"""
|
||||
confirmPayAppendMemo = """\n✉️ %s"""
|
||||
payHelpText = """📖 Hoppalaa… olmadı. %s
|
||||
|
||||
*Komut:* `/pay <invoice>`
|
||||
*Örnek:* `/pay lnbc20n1psscehd...`"""
|
||||
|
||||
# DONATE
|
||||
|
||||
donationSuccess = """🙏 Bağış için teşekkürler."""
|
||||
donationErrorMessage = """🚫 Bağış yapılamadı."""
|
||||
donationProgressMessage = """🧮 Bağışın hazırlanıyor…"""
|
||||
donationFailedMessage = """🚫 Bağış yapılamadı: %s"""
|
||||
donateEnterAmountMessage = """Miktar girdin mi?"""
|
||||
donateValidAmountMessage = """Geçerli bir miktar girdin mi?"""
|
||||
donateHelpText = """📖 Hoppalaa… olmadı. %s
|
||||
|
||||
*Komut:* `/donate <miktar>`
|
||||
*Örnek:* `/donate 1000`"""
|
||||
|
||||
# PHOTO
|
||||
|
||||
photoQrNotRecognizedMessage = """🚫 Lightning Invoice veya LNURL tanımlanamadı. QR Kodunu ortalayarak, boyutlandırarak veya büyüterek tekrar dene."""
|
||||
photoQrRecognizedMessage = """✅ QR Code:
|
||||
`%s`"""
|
||||
|
||||
# LNURL
|
||||
|
||||
lnurlReceiveInfoText = """👇 Bu LNURL kodunu ödeme almak için kullanabilirsin."""
|
||||
lnurlResolvingUrlMessage = """🧮 Adres çözümleniyor…"""
|
||||
lnurlGettingUserMessage = """🧮 Ödeme hazırlanıyor..."""
|
||||
lnurlPaymentFailed = """🚫 Ödeme başarısız: %s"""
|
||||
lnurlInvalidAmountMessage = """🚫 Geçersiz miktar."""
|
||||
lnurlInvalidAmountRangeMessage = """🚫 Miktar %d ve %d sat arasında olmalı."""
|
||||
lnurlNoUsernameMessage = """🚫 LNURL ödemesi almak için bir Telegram kullanıcı ismi seçmelisin."""
|
||||
lnurlHelpText = """📖 Hoppalaa… olmadı. %s
|
||||
|
||||
*Komut:* `/lnurl [miktar] <lnurl>`
|
||||
*Örnek:* `/lnurl LNURL1DP68GUR...`"""
|
||||
|
||||
# LINK
|
||||
|
||||
walletConnectMessage = """🔗 *Cüzdanını bağla*
|
||||
|
||||
⚠️ Bu URL yi veya QR kodunu kimseyle paylaşma. Bu bilgiye ulaşan biri hesabına da ulaşabilir.
|
||||
|
||||
- *BlueWallet:* *New wallet*, *Import wallet*, *Scan or import a file* tıkla ve QR kodunu tarat.
|
||||
- *Zeus:* Aşağıdaki URL’yi kopyala ve *Add a new node*, *Import* (URL’yi), *Save Node Config* tıkla."""
|
||||
couldNotLinkMessage = """🚫 Cüzdanın bağlanamadı. Lütfen daha sonra tekrar dene."""
|
||||
|
||||
# FAUCET
|
||||
|
||||
inlineQueryFaucetTitle = """🚰 Bir Fıçı oluştur."""
|
||||
inlineQueryFaucetDescription = """Komut: @%s faucet <toplam> <kullanıcı_başına>"""
|
||||
inlineResultFaucetTitle = """🚰 Bir %d sat Fıçı oluştur."""
|
||||
inlineResultFaucetDescription = """👉 Fıçı’yı bu sohbete göndermek için tıkla."""
|
||||
|
||||
inlineFaucetMessage = """✅ butonuna basarak Fıçıdan %d sat çek.
|
||||
|
||||
🚰 Kalan: %d/%d sat (%d/%d çekildi)
|
||||
%s"""
|
||||
inlineFaucetEndedMessage = """🚰 Fıçı boşaldı 🍺\n\n🏅 %d sat %d kullanıcıya dağıtıldı."""
|
||||
inlineFaucetAppendMemo = """\n✉️ %s"""
|
||||
inlineFaucetCreateWalletMessage = """%s 👈 ile cüzdanı kullanmak için sohbete başla."""
|
||||
inlineFaucetCancelledMessage = """🚫 Fıçı iptal edildi."""
|
||||
inlineFaucetInvalidPeruserAmountMessage = """🚫 Toplam miktar bölü kullanıcı başına miktar tam sayı olmalı. Bu sayı küsuratlı olmaz."""
|
||||
inlineFaucetInvalidAmountMessage = """🚫 Geçersiz miktar."""
|
||||
inlineFaucetSentMessage = """🚰 %d sat %s a gönderildi."""
|
||||
inlineFaucetReceivedMessage = """🚰 %s sana %d sat gönderdi."""
|
||||
inlineFaucetHelpFaucetInGroup = """Fıçıyı İçinde bot olan bir grupta oluştur veya 👉 Inline komutunu kullan (/advanced daha fazla bilgi)."""
|
||||
inlineFaucetHelpText = """📖 Hoppalaa… olmadı. %s
|
||||
|
||||
*Komut:* `/faucet <toplam> <kullanıcı_başına>`
|
||||
*Örnek:* `/faucet 210 21`"""
|
||||
|
||||
# INLINE SEND
|
||||
|
||||
inlineQuerySendTitle = """💸 Sohbete ödeme gönder."""
|
||||
inlineQuerySendDescription = """Komut: @%s send <miktar> [<kullanıcı>] [<bildirim>]"""
|
||||
inlineResultSendTitle = """💸 %d sat gönder."""
|
||||
inlineResultSendDescription = """👉 Sohbete %d sat göndermek için tıkla."""
|
||||
|
||||
inlineSendMessage = """✅ Butona basarak %s dan ödeme al.\n\n💸 Miktar: %d sat"""
|
||||
inlineSendAppendMemo = """\n✉️ %s"""
|
||||
inlineSendUpdateMessageAccept = """💸 %d sat %s dan %s ye gönderildi."""
|
||||
inlineSendCreateWalletMessage = """%s 👈 ile cüzdanı kullanmak için sohbete başla."""
|
||||
sendYourselfMessage = """📖 Kendi kendine ödeme yapamazsın."""
|
||||
inlineSendFailedMessage = """🚫 Gönderim başarısız."""
|
||||
inlineSendInvalidAmountMessage = """🚫 Miktar 0 dan büyük olmalı."""
|
||||
inlineSendBalanceLowMessage = """🚫 Kredin yetersiz."""
|
||||
|
||||
# INLINE RECEIVE
|
||||
|
||||
inlineQueryReceiveTitle = """🏅 Sohbetten ödeme iste."""
|
||||
inlineQueryReceiveDescription = """Komut: @%s receive <miktar> [<kullanıcı>] [<bildirim>]"""
|
||||
inlineResultReceiveTitle = """🏅 %d sat iste."""
|
||||
inlineResultReceiveDescription = """👉%d sat istemek için tıkla."""
|
||||
|
||||
inlineReceiveMessage = """💸 butonuna basarak %s a öde.\n\n💸 Miktar: %d sat"""
|
||||
inlineReceiveAppendMemo = """\n✉️ %s"""
|
||||
inlineReceiveUpdateMessageAccept = """💸 %d sat %s dan %s ye gönderildi."""
|
||||
inlineReceiveCreateWalletMessage = """%s 👈 ile cüzdanı kullanmak için sohbete başla."""
|
||||
inlineReceiveYourselfMessage = """📖 Kendi kendine ödeme yapamazsın."""
|
||||
inlineReceiveFailedMessage = """🚫 İstek başarısız."""
|
||||
inlineReceiveCancelledMessage = """🚫 İstek iptal edildi."""
|
||||
@@ -1,28 +1,36 @@
|
||||
package telegram
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/str"
|
||||
"github.com/eko/gocache/store"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v2"
|
||||
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func SetUserState(user *lnbits.User, bot *TipBot, stateKey lnbits.UserStateKey, stateData string) {
|
||||
user.StateKey = stateKey
|
||||
user.StateData = stateData
|
||||
UpdateUserRecord(user, *bot)
|
||||
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 ResetUserState(user *lnbits.User, bot *TipBot) {
|
||||
user.ResetState()
|
||||
UpdateUserRecord(user, *bot)
|
||||
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 GetUserStr(user *tb.User) string {
|
||||
@@ -41,14 +49,10 @@ func GetUserStrMd(user *tb.User) string {
|
||||
// if user does not have a username
|
||||
if len(userStr) < 2 && user.FirstName != "" {
|
||||
userStr = fmt.Sprintf("[%s](tg://user?id=%d)", user.FirstName, user.ID)
|
||||
return userStr
|
||||
} else if len(userStr) < 2 {
|
||||
userStr = fmt.Sprintf("[%d](tg://user?id=%d)", user.ID, user.ID)
|
||||
return userStr
|
||||
} else {
|
||||
// escape only if user has a username
|
||||
return str.MarkdownEscape(userStr)
|
||||
}
|
||||
return MarkdownEscape(userStr)
|
||||
}
|
||||
|
||||
func appendUinqueUsersToSlice(slice []*tb.User, i *tb.User) []*tb.User {
|
||||
@@ -60,41 +64,38 @@ func appendUinqueUsersToSlice(slice []*tb.User, i *tb.User) []*tb.User {
|
||||
return append(slice, i)
|
||||
}
|
||||
|
||||
func (bot *TipBot) GetUserBalanceCached(user *lnbits.User) (amount int64, err error) {
|
||||
u, err := bot.Cache.Get(fmt.Sprintf("%s_balance", user.Name))
|
||||
func (bot *TipBot) UserInitializedWallet(user *tb.User) bool {
|
||||
toUser, err := GetUser(user, *bot)
|
||||
if err != nil {
|
||||
return bot.GetUserBalance(user)
|
||||
return false
|
||||
}
|
||||
cachedBalance := u.(int64)
|
||||
return cachedBalance, nil
|
||||
return !toUser.Initialized
|
||||
}
|
||||
|
||||
func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int64, err error) {
|
||||
wallet, err := bot.Client.Info(*user.Wallet)
|
||||
func (bot *TipBot) GetUserBalance(user *tb.User) (amount int, err error) {
|
||||
// get user
|
||||
fromUser, err := GetUser(user, *bot)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[GetUserBalance] Error: Couldn't fetch user %s's info from LNbits: %s", GetUserStr(user.Telegram), err.Error())
|
||||
return
|
||||
}
|
||||
wallet, err := fromUser.Wallet.Info(*fromUser.Wallet)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[GetUserBalance] Error: Couldn't fetch user %s's info from LNbits: %s", GetUserStr(user), err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
user.Wallet.Balance = wallet.Balance
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
fromUser.Wallet.Balance = wallet.Balance
|
||||
err = UpdateUserRecord(fromUser, *bot)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// msat to sat
|
||||
amount = int64(wallet.Balance) / 1000
|
||||
log.Infof("[GetUserBalance] %s's balance: %d sat\n", GetUserStr(user.Telegram), amount)
|
||||
|
||||
// update user balance in cache
|
||||
bot.Cache.Set(
|
||||
fmt.Sprintf("%s_balance", user.Name),
|
||||
amount,
|
||||
&store.Options{Expiration: 30 * time.Second},
|
||||
)
|
||||
amount = int(wallet.Balance) / 1000
|
||||
log.Infof("[GetUserBalance] %s's balance: %d sat\n", GetUserStr(user), amount)
|
||||
return
|
||||
}
|
||||
|
||||
func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, error) {
|
||||
func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) error {
|
||||
user := &lnbits.User{Telegram: tbUser}
|
||||
userStr := GetUserStr(tbUser)
|
||||
log.Printf("[CreateWalletForTelegramUser] Creating wallet for user %s ... ", userStr)
|
||||
@@ -102,20 +103,20 @@ func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, e
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[CreateWalletForTelegramUser] Error: Could not create wallet for user %s", userStr)
|
||||
log.Errorln(errmsg)
|
||||
return user, err
|
||||
return err
|
||||
}
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
tx := bot.database.Save(user)
|
||||
if tx.Error != nil {
|
||||
return tx.Error
|
||||
}
|
||||
log.Printf("[CreateWalletForTelegramUser] Wallet created for user %s. ", userStr)
|
||||
return user, nil
|
||||
return 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
|
||||
func (bot *TipBot) UserHasWallet(user *tb.User) bool {
|
||||
_, err := GetUser(user, *bot)
|
||||
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return false
|
||||
}
|
||||
return lnbitUser, true
|
||||
return true
|
||||
}
|
||||
Reference in New Issue
Block a user