Compare commits

..
40 Commits
Author SHA1 Message Date
3a2c5b2c51 Portuguese (#100)
* For mango-selling grannies in Brazil

* fix

* rename to pt-br.toml

Co-authored-by: Koty <89604768+kotyauditore@users.noreply.github.com>
2021-10-13 09:01:06 +03:00
c7212131fa Fix fr.toml (#99)
* Create fr.toml 

French translation

* Update with correct line breaks

* typo change

* fix mistakes, enable fr.toml

Co-authored-by: Nicolas Bustamante <92287725+nbstme@users.noreply.github.com>
2021-10-13 08:43:37 +03:00
LightningTipBot 88fdb4de9b small fix 2021-10-11 18:20:25 +03:00
Bas SimonsandGitHub 693f12470c Better dutch translations (#95)
* Update nl.toml

better dutch

* Update nl.toml
2021-10-11 09:08:37 +03:00
Nicolas BustamanteandGitHub 887751cb0f small typo (#96) 2021-10-11 09:07:44 +03:00
LightningTipBotandGitHub 08c7ff5113 Fiat price hotfix2 (#94)
* INR added

* also accept currency string

* dividion by 0

* better check
2021-10-08 10:53:33 +03:00
LightningTipBotandGitHub 7c77d268f6 Fiat price hotfix2 (#93)
* INR added

* also accept currency string

* dividion by 0
2021-10-08 10:51:43 +03:00
LightningTipBotandGitHub 61bc3710c0 Fiat price hotfix2 (#92)
* INR added

* also accept currency string
2021-10-08 10:45:29 +03:00
a880d7b044 Contains -> HasPrefix || HasSuffix (#91)
Co-authored-by: LightningTipBot <hWOofXvq4m@mail.com>
2021-10-08 08:42:19 +02:00
LightningTipBotandGitHub 8c7c22b0d8 price checker (#90)
* price checker

* more currencies

* debug messages
2021-10-08 08:35:46 +02:00
94eff98f60 bunt transaction generalization (#73)
* add generalized bunt database transaction

* use bunt tx for inline faucet and send

* use bunt tx for inline receive

* use bunt tx for inline send

* use bunt tx for pay

* fix typo

* readd context

* add generalized bunt database transaction

* use bunt tx for inline faucet and send

* use bunt tx for inline receive

* use bunt tx for inline send

* use bunt tx for pay

* fix typo

* readd context

* some fixes

* tigher error checking

* add CreatedAt and UpdatedAt flags

* check error in GetTransaction

* add bunt transaction package and rename stuff

* use transaction.Base as function receiver for transaction functions

* add transaction.Base.Set function

* fix tiptooltip bunt index

* refactor

* auto update updated at

* refactor

* remove balance from error

* fix updated at

* faucet errors

* add generalized bunt database transaction

* use bunt tx for inline faucet and send

* use bunt tx for inline receive

* use bunt tx for inline send

* use bunt tx for pay

* fix typo

* readd context

* some fixes

* tigher error checking

* add generalized bunt database transaction

* use bunt tx for inline faucet and send

* use bunt tx for inline send

* add CreatedAt and UpdatedAt flags

* check error in GetTransaction

* add bunt transaction package and rename stuff

* use transaction.Base as function receiver for transaction functions

* add transaction.Base.Set function

* fix tiptooltip bunt index

* refactor

* auto update updated at

* fix updated at

* faucet errors

* refactor

* remove balance from error

* rebase fixes

* fix imports

* fix de string

* fix receive and send

* faucet language

* remove pay constructor

* release faucet

* remove redundant inTransaction

* remove constructor

* remove constructor

* transaction get pointer receiver

* send race condition

* inactivate in db

Co-authored-by: LightningTipBot <hWOofXvq4m@mail.com>
2021-10-08 00:46:52 +03:00
lngohumble 6a5f09fa18 Revert "price watcher"
This reverts commit 808a5a3b
2021-10-07 22:08:23 +02:00
LightningTipBot 808a5a3b72 price watcher 2021-10-07 22:53:07 +03:00
903cc3c2e2 Lnurlp comments (#89)
* lnurl comments for RECEIVING

* fix import cycle

* fix import

* rename WebhookServer to Server

* rename LNURLInvoice to Invoice

* add str package. MarkdownEscape lnurl.Invoice comment

* add str package

* check for comment length

* lnurl pay with comment

* lnurl pay with comment

* check for wallet existence

* repackage main to internal

Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-10-07 00:21:21 +03:00
LightningTipBotandGitHub f6ef7933f5 refactor translations (#88)
* refactor translations

* fix print error

* add rest of languages

* remove unnecessary package
2021-10-06 21:32:44 +03:00
48fce72559 Italian translation (#87)
* add it.toml

* fix toml and load localizzazione

* fix commands

* update translation

* fix strings

* remove duplicate

Co-authored-by: lngohumble <lngohumble@gmail.com>
2021-10-06 01:40:16 +03:00
LightningTipBotandGitHub 31caa37657 Inline translations (#85)
* translate faucets

* fix faucet buttons
2021-09-27 00:57:59 +02:00
LightningTipBotandGitHub a9b9d0bfdd translate faucets (#84) 2021-09-27 00:14:35 +02:00
LightningTipBotandGitHub a7a7968d09 fix /pay message (#83) 2021-09-26 23:09:11 +02:00
LightningTipBotandGitHub 7e532f3f01 Get user hotfix1 (#82)
* database error on lookup fail

* still return user skeleton on error
2021-09-26 19:22:53 +02:00
LightningTipBotandGitHub 4d5731bf51 adjust es.toml (#81)
* adjust es.toml

* adjust es.toml
2021-09-26 10:19:56 +02:00
LightningTipBotandGitHub 5784126bbd Amount k (#79)
* amounts with k

* faucet with getAmount
2021-09-25 18:08:23 +02:00
LightningTipBotandGitHub af21ad4bea hotfixes (#78) 2021-09-25 17:50:18 +02:00
LightningTipBotandGitHub 4830928352 I18n hotfix1 (#77)
* fix context for /start

* fix tip from translation
2021-09-25 15:04:53 +02:00
167b581d3e translations (#71)
* squash

* balance too low message

* add context to start

* add translations

* translation readme

* translations for all

* equalize

* new faucet empty message

* commands

* localize

* add more commands

* adjust

* add language code

* add languageCode context

* cancel handler with struct language

* inline objects use their language

* button translations

* send language

* add GetLnbitsUser

* different localizers

* fix publicLanguageCode

* translate balance and donate

* whatever bro

* translateUser

* pull bro

* asd

* Create nl.toml (#74)

* Create nl.toml

* Update nl.toml

* I18n (#75)

* Whatever brah

* Update es.toml

* Whatever brah

* Update nl.toml (#76)

* clean comments

* fix amount

Co-authored-by: lngohumble <lngohumble@gmail.com>
Co-authored-by: maxmerlin78 <91363235+maxmerlin78@users.noreply.github.com>
Co-authored-by: Koty <89604768+kotyauditore@users.noreply.github.com>
2021-09-25 14:07:29 +02:00
LightningTipBotandGitHub 2c51662a75 Send and pay data persistent (#72)
* new lookup function

* use persitant object

* rename to avoid collisions

* send with persistent structs

* add persistant pay struct

* finish up

* clean comments

* revert

* fix ID check

* less logging

* error logging fixed

* payment error verbose

* reply to interceptor for send

* reply to send command if channel
2021-09-22 21:23:53 +02:00
fbbe18d7a7 add interceptor and handler context (#69)
* add interceptor for handler context

* remove user load

* remove UserInitializedWallet

* remove getuser invocation

* add lnbits user to inlineFaucet

* set wallet client

* lnbits user to inline receive

* lnbits user to inline send

* add context to handleInlineReceiveQuery

* add handler.go

* fix help message

* fix handler registration

* rename

* check if reply to is nil

* remove unwanted stuff

* error handlers

* remove client from wallet

* rename force to require

* string fixes

* add intercept.Func

* add PrivateChat check

* remove private chat requirement for anytexthandler

* fix callback

* errors fixed

* fix callback

* loadUser

* do not require

* check type in interceptor

* check type in interceptor

* check for user wallets

* allow send for toUser with wallet but not initialized

* fix reply to context

* mdescape

* strfux

* set state columns only

* update str

* set user now

* anytext should not load user outside pm

* rename endpoint to donationEndpoint

* register uppercase endpoints and add comments

* fix photos in logMessageInterceptor

* reduce log level to trace

Co-authored-by: LightningTipBot <hWOofXvq4m@mail.com>
2021-09-21 21:35:10 +02:00
LightningTipBotandGitHub e3ba16f5d1 better errors (#68)
* better errors

* better log
2021-09-14 17:46:22 +02:00
LightningTipBotandGitHub 39ed394984 wrong balance check (#67) 2021-09-14 11:59:36 +02:00
LightningTipBotandGitHub 1b97544ad5 zapfhahn and kraan (#66) 2021-09-14 11:18:22 +02:00
LightningTipBotandGitHub 7c33234d91 faucet help (#65) 2021-09-14 09:58:54 +02:00
LightningTipBotandGitHub f23e4098e3 add peruser amount (#64)
* add peruser amount

* remove dev edit
2021-09-13 23:53:30 +02:00
LightningTipBotandGitHub 1a073b339b faucet progress bar (#63)
* faucet progress bar

* format
2021-09-13 23:39:00 +02:00
LightningTipBotandGitHub 0653b82c10 add peruser amount to message (#62) 2021-09-13 23:22:17 +02:00
LightningTipBotandGitHub 4a9dcc9601 Inline faucet (#60) 2021-09-13 22:44:43 +02:00
LightningTipBotandGitHub 34d951ee85 fix state reset (#61)
* fix state reset

* fix reference

* ask for amount explicitly
2021-09-13 20:23:59 +02:00
LightningTipBotandGitHub 8af08357d0 tooltip factor messages (#59)
* tooltip factor messages
* init user if not inited
2021-09-10 10:16:49 +02:00
LightningTipBot a19fa50bb8 readme inline send 2021-09-10 09:53:12 +02:00
LightningTipBot 079e490cac rephrase readme 2021-09-10 09:35:59 +02:00
gohumble acf0cb5af6 Initial commit 2021-09-10 08:52:44 +02:00
77 changed files with 7157 additions and 1790 deletions
+49 -12
View File
@@ -29,7 +29,7 @@ After the configuration (see below), start it using the command
### Configuration
You need to edit `config.yaml` before starting the bot.
You need to edit `config.yaml` before you can start the bot.
#### Create a Telegram bot
@@ -39,7 +39,7 @@ First, create a new Telegram bot by starting a conversation with the [@BotFather
You can either use your own LNbits instance (recommended) or create an account at [lnbits.com](https://lnbits.com/) to use their custodial service (easy).
1. Create a wallet in LNbits (`lnbits_url`).
1. Create a wallet in LNbits (reachable by the bot via `lnbits_url`).
2. Get the **Admin key** in the API Info tab of your user (`lnbits_admin_key`).
3. Enable the User Manager extension.
4. Get the **Admin ID** of the User Manager (`lnbits_admin_id`).
@@ -52,26 +52,53 @@ You can either use your own LNbits instance (recommended) or create an account a
#### More configuration
- `webhook_server`: URL that can reach the bot. This is used for creating webhooks with LNbits to receive notifications about payments (optional).
- `db_path`: User database file path.
- `transactions_path`: Transaction log file path.
- `message_dispose_duration`: Duration in seconds after which commands will be deleted from channel (only if the bot is channel admin).
- `transactions_path`: Transaction database file path.
- `buntdb_path`: Object storage database file path.
- `lnbits_webhook_server`: URL that lnbits can reach the bot with. This is used for creating webhooks from LNbits to receive notifications about payments (optional).
- `message_dispose_duration`: Duration in seconds after which `/tip` are deleted from a channel (only if the bot is channel admin).
- `http_proxy` uses a proxy for all LNURL-related outbound requests (optional).
- `lnurl_public_host_name` is the public URL of your lnbits/LndHub (for BlueWallet/Zap support, optional).
- `lnurl_server` is the public URL for inbound LNURL payments and your lightning address host (optional).
## Features
### Commands
#### Commands
```
/tip 🏅 Reply to a message to tip it: /tip <amount> [<memo>]
/balance 👑 Check your balance: /balance
/send 💸 Send funds to a user: /send <amount> <@username> [<memo>]
/invoice ⚡️ Create a Lightning invoice to receive payments: /invoice <amount> [<memo>]
/pay ⚡️ Pay a Lightning invoice: /pay <invoice>
/send 💸 Send funds to a user: /send <amount> <@user> or <user@domain.com> [<memo>]
/invoice ⚡️ Receive over Lightning: /invoice <amount> [<memo>]
/pay ⚡️ Pay over Lightning: /pay <invoice>
/help 📖 Read this help.
/info 📚 More info.
/donate 🙏 Donate to @LightningTipBot: /donate <amount>
/advanced 🤖 Read the advanced help.
/basics 📚 More info.
/donate ❤️ Donate to the project: /donate <amount>
```
#### Advanced commands
```
/link 🔗 Link your wallet to BlueWallet or Zeus
/lnurl ⚡️ Lnurl receive or pay: /lnurl or /lnurl <lnurl>
```
### Inline commands
```
send 💸 Send sats to chat: @LightningTipBot send <amount> [<memo>]
```
📖 You can use inline commands in every chat, even in private conversations. Wait a second after entering an inline command and click the result, don't press enter.
### Inline send
You can use inline commands to send payments to anyone who can read your messages, even inside private chats and group chat in which the bot isn't part of. For that, you need to trigger an [inline command](https://core.telegram.org/bots/inline). Here is how it works: Enter the name of the bot (`@LightningTipBot`) and the command you want to trigger (`send 13 Hi friend!`). When the result pops up above the text field, click it to send it to the chat. Do not press enter.
<p align="center">
<img alt="Send sats inside any chat, including private conversations and groups." src="resources/inline_send.png" >
</p>
### Live tooltips
The bot replies to a tipped message to indicate to all participants how many and what amount of tips a post has received. This tooltip will be updated as new tips are given to a post.
@@ -80,9 +107,18 @@ The bot replies to a tipped message to indicate to all participants how many and
<img alt="How to set up a lnbits wallet and the User Manager extension." src="resources/tooltips.png" >
</p>
### LNURL server
Users can send and receive via . For this to work, you need to set the `lnurl_public_server` in `config.yaml`. The bot will then host a LNURL endpoint at `.well-known/lnurlp/username` which handles the data exchange with other wallets. You can set `http_proxy` in `config.yaml` to send outbound requests only via an HTTP proxy.
### Send and receive via Lightning Address
Every user has a [Lightning Address](https://lightningaddress.com/) a la `username@host.com` with which they can send to via `/send <amount> <user@domain.com>` and receive from other wallets.
### Link to BlueWallet or Zap
Every user can link their wallet to an external app like [Bluewallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/) by using the command `/link`. If you host the bot, you will have to enable the LndHub extension in LNbits. You also need to edit the `lnbits_public_url` entry in `config.yaml` accordingly to an address that can be reached.
Every user can link their wallet to an external app like [Bluewallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/) by using the command `/link`. If you host the bot, you will have to enable the LndHub extension in LNbits. You also need to edit the `lnbits_public_url` entry in `config.yaml` accordingly to an address that can be reached by the user's wallet (Tor should be fine as well).
<p align="center">
<img alt="QR code payment example." src="resources/lndhub.png" >
@@ -106,3 +142,4 @@ To minimize the clutter all the heavy tipping can cause in a group chat, the bot
- [telebot](https://github.com/tucnak/telebot) – A Telegram bot framework in Go.
- [gozxing](https://github.com/makiuchi-d/gozxing) – barcode image processing library in Go.
- [ln-decodepay](https://github.com/fiatjaf/ln-decodepay) – Lightning Network BOLT11 invoice decoder.
- [go-lnurl](https://github.com/fiatjaf/go-lnurl) - Helpers for building lnurl support into services.
-38
View File
@@ -1,38 +0,0 @@
package main
import (
"errors"
"strconv"
"strings"
)
func getArgumentFromCommand(input string, which int) (output string, err error) {
if len(strings.Split(input, " ")) < which+1 {
return "", errors.New("Message doesn't contain enough arguments")
}
output = strings.Split(input, " ")[which]
return output, nil
}
func decodeAmountFromCommand(input string) (amount int, err error) {
if len(strings.Split(input, " ")) < 2 {
errmsg := "Message doesn't contain any amount"
// log.Errorln(errmsg)
return 0, errors.New(errmsg)
}
amount, err = getAmount(input)
return amount, nil
}
func getAmount(input string) (amount int, err error) {
amount, err = strconv.Atoi(strings.Split(input, " ")[1])
if err != nil {
return 0, err
}
if amount < 1 {
errmsg := "Error: Amount must be greater than 0"
// log.Errorln(errmsg)
return 0, errors.New(errmsg)
}
return amount, err
}
-130
View File
@@ -1,130 +0,0 @@
package main
import (
"fmt"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/tucnak/telebot.v2"
"gorm.io/gorm"
)
type TipBot struct {
database *gorm.DB
logger *gorm.DB
telegram *telebot.Bot
client *lnbits.Client
tips map[int][]*Message
}
var (
paymentConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
btnCancelPay = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_pay")
btnPay = paymentConfirmationMenu.Data("✅ Pay", "confirm_pay")
sendConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
btnCancelSend = sendConfirmationMenu.Data("🚫 Cancel", "cancel_send")
btnSend = sendConfirmationMenu.Data("✅ Send", "confirm_send")
botWalletInitialisation = sync.Once{}
telegramHandlerRegistration = sync.Once{}
)
// NewBot migrates data and creates a new bot
func NewBot() TipBot {
db, txLogger := migration()
return TipBot{
database: db,
logger: txLogger,
tips: make(map[int][]*Message, 0),
}
}
// newTelegramBot will create a new telegram bot.
func newTelegramBot() *tb.Bot {
tgb, err := tb.NewBot(tb.Settings{
Token: Configuration.ApiKey,
Poller: &tb.LongPoller{Timeout: 60 * time.Second},
ParseMode: tb.ModeMarkdown,
})
if err != nil {
panic(err)
}
return tgb
}
// initBotWallet will create / initialize the bot wallet
// todo -- may want to derive user wallets from this specific bot wallet (master wallet), since lnbits usermanager extension is able to do that.
func (bot TipBot) initBotWallet() error {
botWalletInitialisation.Do(func() {
err := bot.initWallet(bot.telegram.Me)
if err != nil {
log.Errorln(fmt.Sprintf("[initBotWallet] Could not initialize bot wallet: %s", err.Error()))
return
}
})
return nil
}
// registerTelegramHandlers will register all telegram handlers.
func (bot TipBot) registerTelegramHandlers() {
telegramHandlerRegistration.Do(func() {
// Set up handlers
var endpointHandler = map[string]interface{}{
"/tip": bot.tipHandler,
"/pay": bot.confirmPaymentHandler,
"/invoice": bot.invoiceHandler,
"/balance": bot.balanceHandler,
"/start": bot.startHandler,
"/send": bot.confirmSendHandler,
"/help": bot.helpHandler,
"/info": bot.infoHandler,
"/donate": bot.donationHandler,
"/advanced": bot.advancedHelpHandler,
"/link": bot.lndhubHandler,
tb.OnPhoto: bot.privatePhotoHandler,
tb.OnText: bot.anyTextHandler,
}
// assign handler to endpoint
for endpoint, handler := range endpointHandler {
log.Debugf("Registering: %s", endpoint)
bot.telegram.Handle(endpoint, handler)
// if the endpoint is a string command (not photo etc)
if strings.HasPrefix(endpoint, "/") {
// register upper case versions as well
bot.telegram.Handle(strings.ToUpper(endpoint), handler)
}
}
// button handlers
// for /pay
bot.telegram.Handle(&btnPay, bot.payHandler)
bot.telegram.Handle(&btnCancelPay, bot.cancelPaymentHandler)
// for /send
bot.telegram.Handle(&btnSend, bot.sendHandler)
bot.telegram.Handle(&btnCancelSend, bot.cancelSendHandler)
})
}
// Start will initialize the telegram bot and lnbits.
func (bot TipBot) Start() {
// set up lnbits api
bot.client = lnbits.NewClient(Configuration.LnbitsKey, Configuration.LnbitsUrl)
// set up telebot
bot.telegram = newTelegramBot()
log.Infof("[Telegram] Authorized on account @%s", bot.telegram.Me.Username)
// initialize the bot wallet
err := bot.initBotWallet()
if err != nil {
log.Errorf("Could not initialize bot wallet: %s", err.Error())
}
bot.registerTelegramHandlers()
lnbits.NewWebhook(Configuration.WebhookServer, bot.telegram, bot.client, bot.database)
bot.telegram.Start()
}
+7 -6
View File
@@ -6,10 +6,11 @@
4 - Paste this:
help - Read the help.
balance - Check your balance.
tip - Reply to a message to tip. Example: /tip 50
send - Send funds to a Telegram user. Example: /send 100 @LightningTipBot
invoice - Create a Lightning invoice to receive payments. Example: /invoice 1000
pay - Pay a Lightning invoice. Example: /pay lnbc10n1ps...
donate - Donate to the project: Example: /donate 1000
balance - Check balance.
tip - Reply to a message to tip: /tip 50
send - Send funds to a user: /send 100 @LightningTipBot
invoice - Receive with Lightning: /invoice 1000
pay - Pay with Lightning: /pay lnbc10n1ps...
donate - Donate: /donate 1000
faucet - Create a faucet: /faucet 2100 21
advanced - Advanced help
-22
View File
@@ -1,22 +0,0 @@
package main
import "github.com/jinzhu/configor"
var Configuration = struct {
AdminKey string `json:"lnbits_admin_id" yaml:"lnbits_admin_id"`
LnbitsKey string `json:"lnbits_admin_key" yaml:"lnbits_admin_key"`
LnbitsUrl string `json:"lnbits_url" yaml:"lnbits_url"`
LnbitsPublicUrl string `json:"lnbits_public_url" yaml:"lnbits_public_url"`
WebhookServer string `json:"webhook_server" yaml:"webhook_server"`
ApiKey string `json:"telegram_api_key" yaml:"telegram_api_key"`
DbPath string `json:"db_path" yaml:"db_path"`
TransactionsPath string `json:"transactions_path" yaml:"transactions_path"`
MessageDisposeDuration int64 `json:"message_dispose_duration" yaml:"message_dispose_duration"`
}{}
func init() {
err := configor.Load(&Configuration, "config.yaml")
if err != nil {
panic(err)
}
}
+17 -9
View File
@@ -1,9 +1,17 @@
telegram_api_key: "1234"
webhook_server: "http://0.0.0.0:1234"
lnbits_url: "http://127.0.0.1:1234"
lnbits_public_url: "http://*.onion:1234"
lnbits_admin_key: "1234"
lnbits_admin_id: "3212"
db_path: "data/bot.db"
transactions_path: "data/transactions.db"
message_dispose_duration: 10
bot:
http_proxy: ""
lnurl_public_host_name: "mylnurl.com"
lnurl_server: "https://mylnurl.com"
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"
-73
View File
@@ -1,73 +0,0 @@
package main
import (
"fmt"
"reflect"
"strconv"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
tb "gopkg.in/tucnak/telebot.v2"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func migration() (db *gorm.DB, txLogger *gorm.DB) {
txLogger, err := gorm.Open(sqlite.Open(Configuration.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
if err != nil {
panic("Initialize orm failed.")
}
orm, err := gorm.Open(sqlite.Open(Configuration.DbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
if err != nil {
panic("Initialize orm failed.")
}
err = orm.AutoMigrate(&lnbits.User{})
if err != nil {
panic(err)
}
err = txLogger.AutoMigrate(&Transaction{})
if err != nil {
panic(err)
}
return orm, txLogger
}
// GetUser from telegram user. Update the user if user information changed.
func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
user := &lnbits.User{Name: strconv.Itoa(u.ID)}
tx := bot.database.First(user)
if tx.Error != nil {
errmsg := fmt.Sprintf("[GetUser] Couldn't fetch %s's info from database.", GetUserStr(u))
log.Warnln(errmsg)
return user, tx.Error
}
defer func() {
user.Wallet.Client = bot.client
}()
var err error
go func() {
if !reflect.DeepEqual(u, user.Telegram) {
// update possibly changed user details in database
user.Telegram = u
err = UpdateUserRecord(user, bot)
if err != nil {
log.Warnln(fmt.Sprintf("[UpdateUserRecord] %s", err.Error()))
}
}
}()
return user, err
}
func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
tx := bot.database.Save(user)
if tx.Error != nil {
errmsg := fmt.Sprintf("[UpdateUserRecord] Error: Couldn't update %s's info in database.", GetUserStr(user.Telegram))
log.Errorln(errmsg)
return tx.Error
}
log.Debugf("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
return nil
}
+8 -1
View File
@@ -3,14 +3,21 @@ module github.com/LightningTipBot/LightningTipBot
go 1.15
require (
github.com/BurntSushi/toml v0.3.1
github.com/fiatjaf/go-lnurl v1.4.0
github.com/fiatjaf/ln-decodepay v1.1.0
github.com/gorilla/mux v1.8.0
github.com/imroc/req v0.3.0
github.com/jinzhu/configor v1.2.1
github.com/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/sirupsen/logrus v1.2.0
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
github.com/tidwall/btree v0.6.1 // indirect
github.com/tidwall/buntdb v1.2.6
github.com/tidwall/gjson v1.8.1
github.com/tidwall/pretty v1.2.0 // indirect
golang.org/x/text v0.3.5
gopkg.in/tucnak/telebot.v2 v2.3.5
gorm.io/driver/sqlite v1.1.4
gorm.io/gorm v1.21.12
+36 -3
View File
@@ -63,6 +63,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
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/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
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/ln-decodepay v1.1.0 h1:HigjqNH+ApiO6gm7RV23jXNFuvwq+zgsWl4BJAfPWwE=
github.com/fiatjaf/ln-decodepay v1.1.0/go.mod h1:2qdTT95b8Z4dfuxiZxXuJ1M7bQ9CrLieEA1DKC50q6s=
github.com/frankban/quicktest v1.2.2/go.mod h1:Qh/WofXFeiAFII1aEBu529AtJo6Zg2VHscnEsbBnJ20=
@@ -145,8 +147,6 @@ github.com/lightningnetwork/lnd/queue v1.0.3 h1:5ufYVE7lh9GJnL1wOoeO3bZ3aAHWNnkN
github.com/lightningnetwork/lnd/queue v1.0.3/go.mod h1:YTkTVZCxz8tAYreH27EO3s8572ODumWrNdYW2E/YKxg=
github.com/lightningnetwork/lnd/ticker v1.0.0 h1:S1b60TEGoTtCe2A0yeB+ecoj/kkS4qpwh6l+AkQEZwU=
github.com/lightningnetwork/lnd/ticker v1.0.0/go.mod h1:iaLXJiVgI1sPANIF2qYYUJXjoksPNvGNYowB8aRbpX0=
github.com/liyue201/goqr v0.0.0-20200803022322-df443203d4ea h1:uyJ13zfy6l79CM3HnVhDalIyZ4RJAyVfDrbnfFeJoC4=
github.com/liyue201/goqr v0.0.0-20200803022322-df443203d4ea/go.mod h1:w4pGU9PkiX2hAWyF0yuHEHmYTQFAd6WHzp6+IY7JVjE=
github.com/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=
@@ -160,6 +160,9 @@ github.com/miekg/dns v0.0.0-20171125082028-79bfde677fa8 h1:PRMAcldsl4mXKJeRNB/KV
github.com/miekg/dns v0.0.0-20171125082028-79bfde677fa8/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/nicksnyder/go-i18n v1.10.1 h1:isfg77E/aCD7+0lD/D00ebR2MV5vgeQ276WYyDaCRQc=
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/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
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=
@@ -193,13 +196,40 @@ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
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/tidwall/btree v0.6.0 h1:JLYAFGV+1gjyFi3iQbO/fupBin+Ooh7dxqVV0twJ1Bo=
github.com/tidwall/btree v0.6.0/go.mod h1:TzIRzen6yHbibdSfK6t8QimqbUnoxUSrZfeW7Uob0q4=
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.6 h1:eS0QSmzHfCKjxxYGh8eH6wnK5VLsJ7UjyyIr29JmnEg=
github.com/tidwall/buntdb v1.2.6/go.mod h1:zpXqlA5D2772I4cTqV3ifr2AZihDgi8FV7xAQu6edfc=
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.8.0 h1:Qt+orfosKn0rbNTZqHYDqBrmm3UDA4KRkv70fDzG+PQ=
github.com/tidwall/gjson v1.8.0/go.mod h1:5/xDoumyyDNerp2U36lyolv46b3uF/9Bu6OfyQ9GImk=
github.com/tidwall/gjson v1.8.1 h1:8j5EE9Hrh3l9Od1OIEDAb7IpezNA20UdRngNAj5N0WU=
github.com/tidwall/gjson v1.8.1/go.mod h1:5/xDoumyyDNerp2U36lyolv46b3uF/9Bu6OfyQ9GImk=
github.com/tidwall/grect v0.1.2 h1:wKVeQVZhjaFCKTTlpkDe3Ex4ko3cMGW3MRKawRe8uQ4=
github.com/tidwall/grect v0.1.2/go.mod h1:v+n4ewstPGduVJebcp5Eh2WXBJBumNzyhK8GZt4gHNw=
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.0.3 h1:FQUVvBImDutD8wJLN6c5eMzWtjgONK9MwIBCOrUJKeE=
github.com/tidwall/match v1.0.3/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.1.0 h1:K3hMW5epkdAVwibsQEfR/7Zj0Qgt4DxtNumTq/VloO8=
github.com/tidwall/pretty v1.1.0/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/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=
go.etcd.io/bbolt v1.3.3 h1:MUGmc65QhB3pIlaQ5bB4LwqSj6GIonVJXpZiaKNyaKk=
@@ -243,6 +273,7 @@ golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7w
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.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/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
@@ -277,6 +308,8 @@ gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bl
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.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
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=
-73
View File
@@ -1,73 +0,0 @@
package main
import (
tb "gopkg.in/tucnak/telebot.v2"
)
const (
helpMessage = "ℹ️ *Info*\n_This bot is a Bitcoin Lightning ⚡️ wallet that can sends tips on Telegram. To tip, add the bot to a group chat. The basic unit of tips are Satoshis (sat). 100,000,000 sat = 1 Bitcoin. There will only ever be 21 Million Bitcoin. Type /info for more._\n\n" +
"❤️ *Donate*\n" +
"_This bot charges no fees but costs satoshis to operate. If you like the bot, please consider supporting this project with a donation. To donate, use_ `/donate 1000`\n\n" +
"⚙️ *Commands*\n" +
"*/tip* 🏅 Reply to a message to tip: `/tip <amount> [<memo>]`\n" +
"*/balance* 👑 Check balance: `/balance`\n" +
"*/send* 💸 Send funds to a Telegram user: `/send <amount> <@user> [<memo>]`\n" +
"*/invoice* ⚡️ Receive over Lightning: `/invoice <amount> [<memo>]`\n" +
"*/pay* ⚡️ Pay over Lightning: `/pay <invoice>`\n" +
"*/donate* ❤️ Donate to the project: `/donate 1000`\n" +
"*/advanced* 🤖 Read the advanced help.\n" +
"*/help* 📖 Read this help."
infoMessage = "🧡 *Bitcoin*\n" +
"_Bitcoin is the currency of the internet. It is permissionless and decentralized and has no masters and no controling authority. Bitcoin is sound money that is faster, more secure, and more inclusive than the legacy financial system._\n\n" +
"🧮 *Economnics*\n" +
"_The smallest unit of Bitcoin are Satoshis (sat) and 100,000,000 sat = 1 Bitcoin. There will only ever be 21 Million Bitcoin. The fiat currency value of Bitcoin can change daily. However, if you live on a Bitcoin standard 1 sat will always equal 1 sat._\n\n" +
"⚡️ *The Lightning Network*\n" +
"_The Lightning Network is a payment protocol that enables fast and cheap Bitcoin payments that require almost no energy. It is what scales Bitcoin to the billions of people around the world._\n\n" +
"📲 *Lightning Wallets*\n" +
"_Your funds on this bot can be sent to any other Lightning wallet and vice versa. Recommended Lightning wallets for your phone are_ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (non-custodial), or_ [Wallet of Satoshi](https://www.walletofsatoshi.com/) _(easy)_.\n\n" +
"📄 *Open Source*\n" +
"_This bot is free and_ [open source](https://github.com/LightningTipBot/LightningTipBot) _software. You can run it on your own computer and use it in your own community._\n\n" +
"✈️ *Telegram*\n" +
"_Add this bot to your Telegram group chat to /tip posts. If you make the bot admin of the group it will also clean up commands to keep the chat tidy._\n\n" +
// "🏛 *Terms*\n" +
// "_We are not custodian of your funds. Any amount you load onto your wallet will be legally considered a donation that belongs to us. We will act in your best interest but we're also aware that the situation without KYC is tricky until we figure something out. Do not give us all your money. Be aware that this bot is in beta development. Use at your own risk._\n\n" +
"❤️ *Donate*\n" +
"_This bot charges no fees but costs satoshis to operate. If you like the bot, please consider supporting this project with a donation. To donate, To donate, use_ `/donate 1000`"
advancedMessage = "🤖 *Advanced commands*\n\n" +
"*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)\n"
)
func (bot TipBot) helpHandler(m *tb.Message) {
// check and print all commands
bot.anyTextHandler(m)
if !m.Private() {
// delete message
NewMessage(m).Dispose(0, bot.telegram)
}
bot.telegram.Send(m.Sender, helpMessage, tb.NoPreview)
return
}
func (bot TipBot) infoHandler(m *tb.Message) {
// check and print all commands
bot.anyTextHandler(m)
if !m.Private() {
// delete message
NewMessage(m).Dispose(0, bot.telegram)
}
bot.telegram.Send(m.Sender, infoMessage, tb.NoPreview)
return
}
func (bot TipBot) advancedHelpHandler(m *tb.Message) {
// check and print all commands
bot.anyTextHandler(m)
if !m.Private() {
// delete message
NewMessage(m).Dispose(0, bot.telegram)
}
bot.telegram.Send(m.Sender, advancedMessage, tb.NoPreview)
return
}
+81
View File
@@ -0,0 +1,81 @@
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"`
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 + "/"
}
}
}
+32
View File
@@ -0,0 +1,32 @@
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)
}
+34
View File
@@ -0,0 +1,34 @@
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")
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
}
+5 -6
View File
@@ -74,14 +74,13 @@ func (c *Client) CreateWallet(userId, walletName, adminId string) (wal Wallet, e
return
}
err = resp.ToJSON(&wal)
wal.Client = c
return
}
// Invoice creates an invoice associated with this wallet.
func (c Client) Invoice(params InvoiceParams, w Wallet) (lntx BitInvoice, err error) {
func (w Wallet) Invoice(params InvoiceParams, c *Client) (lntx BitInvoice, err error) {
c.header["X-Api-Key"] = w.Adminkey
resp, err := req.Post(c.url+"/api/v1/payments", w.header, req.BodyJSON(&params))
resp, err := req.Post(c.url+"/api/v1/payments", c.header, req.BodyJSON(&params))
if err != nil {
return
}
@@ -100,7 +99,7 @@ func (c Client) Invoice(params InvoiceParams, w Wallet) (lntx BitInvoice, err er
// Info returns wallet information
func (c Client) Info(w Wallet) (wtx Wallet, err error) {
c.header["X-Api-Key"] = w.Adminkey
resp, err := req.Get(w.url+"/api/v1/wallet", w.header, nil)
resp, err := req.Get(c.url+"/api/v1/wallet", c.header, nil)
if err != nil {
return
}
@@ -135,9 +134,9 @@ func (c Client) Wallets(w User) (wtx []Wallet, err error) {
}
// Pay pays a given invoice with funds from the wallet.
func (c Client) Pay(params PaymentParams, w Wallet) (wtx BitInvoice, err error) {
func (w Wallet) Pay(params PaymentParams, c *Client) (wtx BitInvoice, err error) {
c.header["X-Api-Key"] = w.Adminkey
resp, err := req.Post(c.url+"/api/v1/payments", w.header, req.BodyJSON(&params))
resp, err := req.Post(c.url+"/api/v1/payments", c.header, req.BodyJSON(&params))
if err != nil {
return
}
+13 -22
View File
@@ -1,6 +1,8 @@
package lnbits
import (
"time"
"github.com/imroc/req"
tb "gopkg.in/tucnak/telebot.v2"
)
@@ -20,24 +22,30 @@ 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"`
}
type UserStateKey int
const (
UserStateConfirmPayment = iota + 1
UserStateConfirmSend
UserStateLNURLEnterAmount
UserStateConfirmLNURLPay
)
type UserStateKey int
func (u *User) ResetState() {
u.StateData = ""
u.StateKey = 0
}
type InvoiceParams struct {
Out bool `json:"out"`
Amount int64 `json:"amount"`
Memo string `json:"memo"` // the invoice description.
Webhook string `json:"webhook,omitempty"`
Out bool `json:"out"` // must be True if invoice is payed, False if invoice is received
Amount int64 `json:"amount"` // amount in MilliSatoshi
Memo string `json:"memo,omitempty"` // the invoice memo.
Webhook string `json:"webhook,omitempty"` // the webhook to fire back to when payment is received.
DescriptionHash string `json:"description_hash,omitempty"` // the invoice description hash.
}
type PaymentParams struct {
@@ -70,7 +78,6 @@ func (err Error) Error() string {
}
type Wallet struct {
*Client `gorm:"-"`
ID string `json:"id" gorm:"id"`
Adminkey string `json:"adminkey"`
Inkey string `json:"inkey"`
@@ -82,19 +89,3 @@ 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"`
}
-91
View File
@@ -1,91 +0,0 @@
package lnbits
import (
"encoding/json"
"fmt"
"net"
"strings"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
"github.com/gorilla/mux"
tb "gopkg.in/tucnak/telebot.v2"
"net/http"
"time"
)
const (
invoiceReceivedMessage = "⚡️ You've received %d sat."
)
type WebhookServer struct {
httpServer *http.Server
bot *tb.Bot
c *Client
database *gorm.DB
}
func NewWebhook(webhookServer string, bot *tb.Bot, client *Client, database *gorm.DB) *WebhookServer {
if !strings.Contains(webhookServer, "://") {
log.Fatal("invalid webhook server configuration. please add a scheme.")
}
_, port, err := net.SplitHostPort(strings.Split(webhookServer, "//")[1])
if err != nil {
return nil
}
srv := &http.Server{
Addr: fmt.Sprintf("0.0.0.0:%s", port),
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
apiServer := &WebhookServer{
c: client,
database: database,
bot: bot,
httpServer: srv,
}
apiServer.httpServer.Handler = apiServer.newRouter()
go apiServer.httpServer.ListenAndServe()
return apiServer
}
func (w *WebhookServer) GetUserByWalletId(walletId string) (*User, error) {
user := &User{}
tx := w.database.Where("wallet_id = ?", walletId).First(user)
if tx.Error != nil {
return user, tx.Error
}
user.Wallet.Client = w.c
return user, nil
}
func (w *WebhookServer) newRouter() *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/", w.receive).Methods(http.MethodPost)
return router
}
func (w WebhookServer) receive(writer http.ResponseWriter, request *http.Request) {
depositEvent := Webhook{}
request.Header.Del("content-length")
err := json.NewDecoder(request.Body).Decode(&depositEvent)
if err != nil {
writer.WriteHeader(400)
return
}
user, err := w.GetUserByWalletId(depositEvent.WalletID)
if err != nil {
writer.WriteHeader(400)
return
}
log.Infoln(fmt.Sprintf("[WebHook] User %s (%d) received invoice of %d sat.", user.Telegram.Username, user.Telegram.ID, depositEvent.Amount/1000))
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(invoiceReceivedMessage, depositEvent.Amount/1000))
if err != nil {
log.Errorln(err)
}
writer.WriteHeader(200)
}
+123
View File
@@ -0,0 +1,123 @@
package webhook
import (
"encoding/json"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"time"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"net/http"
"github.com/gorilla/mux"
tb "gopkg.in/tucnak/telebot.v2"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
)
const (
// invoiceReceivedMessage = "⚡️ You received %d sat."
)
type Server struct {
httpServer *http.Server
bot *tb.Bot
c *lnbits.Client
database *gorm.DB
buntdb *storage.DB
}
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"`
}
func NewServer(bot *telegram.TipBot) *Server {
srv := &http.Server{
Addr: internal.Configuration.Lnbits.WebhookServerUrl.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.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) {
depositEvent := Webhook{}
// need to delete the header otherwise the Decode will fail
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(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), depositEvent.Amount/1000))
if err != nil {
log.Errorln(err)
}
// if this invoice is saved in bunt.db, we load it and display the comment from an LNURL invoice
tx := &lnurl.Invoice{PaymentHash: depositEvent.PaymentHash}
err = w.buntdb.Get(tx)
if err != nil {
log.Errorln(err)
} else {
if len(tx.Comment) > 0 {
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(`✉️ %s`, str.MarkdownEscape(tx.Comment)))
if err != nil {
log.Errorln(err)
}
}
}
writer.WriteHeader(200)
}
+208
View File
@@ -0,0 +1,208 @@
package lnurl
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/fiatjaf/go-lnurl"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
type Invoice struct {
PaymentRequest string `json:"payment_request"`
PaymentHash string `json:"payment_hash"`
Amount int64 `json:"amount"`
Comment string `json:"comment"`
ToUser *lnbits.User `json:"to_user"`
CreatedAt time.Time `json:"created_at"`
Paid bool `json:"paid"`
PaidAt time.Time `json:"paid_at"`
}
func (msg Invoice) Key() string {
return fmt.Sprintf("payment-hash:%s", msg.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("[serveLNURLpSecond] Form value 'amount' is not set"))
return
}
amount, parseError := strconv.Atoi(stringAmount)
if parseError != nil {
NotFoundHandler(writer, fmt.Errorf("[serveLNURLpSecond] Couldn't cast amount to int %v", parseError))
return
}
comment := request.FormValue("comment")
if len(comment) > CommentAllowed {
NotFoundHandler(writer, fmt.Errorf("[serveLNURLpSecond] 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)
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.LNURLPayResponse1, 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)
jsonMeta, err := json.Marshal(metadata)
if err != nil {
return nil, err
}
return &lnurl.LNURLPayResponse1{
LNURLResponse: lnurl.LNURLResponse{Status: statusOk},
Tag: payRequestTag,
Callback: callbackURL.String(),
CallbackURL: callbackURL, // probably no need to set this here
MinSendable: minSendable,
MaxSendable: MaxSendable,
EncodedMetadata: string(jsonMeta),
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 int64, comment string) (*lnurl.LNURLPayResponse2, error) {
log.Infof("[LNURL] Serving invoice for user %s", username)
if amount < minSendable || amount > MaxSendable {
// amount is not ok
return &lnurl.LNURLPayResponse2{
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.LNURLPayResponse2{
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{}
tx := w.database.Where("telegram_username = ?", strings.ToLower(username)).First(user)
if tx.Error != nil {
return &lnurl.LNURLPayResponse2{
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.LNURLPayResponse2{
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.LNURLPayResponse2
// 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 / 1000,
Out: false,
DescriptionHash: descriptionHash,
Webhook: w.WebhookServer},
w.c)
if err != nil {
err = fmt.Errorf("[serveLNURLpSecond] Couldn't create invoice: %v", err)
resp = &lnurl.LNURLPayResponse2{
LNURLResponse: lnurl.LNURLResponse{
Status: statusError,
Reason: "Couldn't create invoice."},
}
return resp, err
}
// save invoice struct for later use
runtime.IgnoreError(w.buntdb.Set(
Invoice{
ToUser: user,
Amount: amount,
Comment: comment,
PaymentRequest: invoice.PaymentRequest,
PaymentHash: invoice.PaymentHash,
CreatedAt: time.Now(),
}))
return &lnurl.LNURLPayResponse2{
LNURLResponse: lnurl.LNURLResponse{Status: statusOk},
PR: invoice.PaymentRequest,
Routes: make([][]lnurl.RouteInfo, 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) {
jsonMeta, err := json.Marshal(metadata)
if err != nil {
return "", err
}
hash := sha256.Sum256([]byte(string(jsonMeta)))
hashString := hex.EncodeToString(hash[:])
return hashString, nil
}
// metaData returns the metadata that is sent in the first response
// and is used again in the second response to verify the description hash
func (w Server) metaData(username string) lnurl.Metadata {
return lnurl.Metadata{
{"text/identifier", fmt.Sprintf("%s@%s", username, w.callbackHostname.Hostname())},
{"text/plain", fmt.Sprintf("Pay to %s@%s", username, w.callbackHostname.Hostname())}}
}
+81
View File
@@ -0,0 +1,81 @@
package lnurl
import (
"encoding/json"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
"net/http"
"net/url"
"time"
"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 = 256
)
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
}
+125
View File
@@ -0,0 +1,125 @@
package price
import (
"fmt"
"io/ioutil"
"net"
"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 exchange, 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, ok := err.(net.Error); ok && err.Timeout() {
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")
fprice, err := strconv.ParseFloat(strings.TrimSpace(price.String()), 64)
if err != nil {
log.Debug(err)
return 0, err
}
return fprice, nil
}
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, ok := err.(net.Error); ok && err.Timeout() {
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")
fprice, err := strconv.ParseFloat(strings.TrimSpace(price.String()), 64)
if err != nil {
log.Debug(err)
return 0, err
}
return fprice, nil
}
+15
View File
@@ -0,0 +1,15 @@
package runtime
import log "github.com/sirupsen/logrus"
// accepts error and logs error message. Used to prevent warnings when errors not caught.
func IgnoreError(err error) {
if err != nil {
log.WithFields(log.Fields{"module": "[ERROR]", "error": err.Error()}).Errorf("catching ignored error")
}
}
func IgnoreErrorMultiReturn(i interface{}, err error) {
if err != nil {
log.WithFields(log.Fields{"module": "[ERROR]", "error": err.Error()}).Errorf("catching ignored error")
}
}
+100
View File
@@ -0,0 +1,100 @@
package storage
import (
"encoding/json"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
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.
// todo -- not ascend users index
func (db *DB) Delete(index string, object Storable) error {
return db.Update(func(tx *buntdb.Tx) error {
var delkeys []string
runtime.IgnoreError(
tx.Ascend(index, func(key, value string) bool {
if key == object.Key() {
delkeys = append(delkeys, key)
}
return true
}),
)
for _, k := range delkeys {
if _, err := tx.Delete(k); err != nil {
return err
}
}
return nil
})
}
@@ -0,0 +1,98 @@
package transaction
import (
"fmt"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
)
type Base struct {
ID string `json:"id"`
Active bool `json:"active"`
InTransaction bool `json:"intransaction"`
CreatedAt time.Time `json:"created"`
UpdatedAt time.Time `json:"updated"`
}
type Option func(b *Base)
func ID(id string) Option {
return func(btx *Base) {
btx.ID = id
}
}
func New(opts ...Option) *Base {
btx := &Base{
Active: true,
InTransaction: false,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
for _, opt := range opts {
opt(btx)
}
return btx
}
func (tx Base) Key() string {
return tx.ID
}
func (tx *Base) Lock(s storage.Storable, db *storage.DB) error {
// immediatelly set intransaction to block duplicate calls
tx.InTransaction = true
err := tx.Set(s, db)
if err != nil {
return err
}
return nil
}
func (tx *Base) Release(s storage.Storable, db *storage.DB) error {
// immediatelly set intransaction to block duplicate calls
tx.InTransaction = false
err := tx.Set(s, db)
if err != nil {
return err
}
return nil
}
func (tx *Base) Inactivate(s storage.Storable, db *storage.DB) error {
tx.Active = false
err := tx.Set(s, db)
if err != nil {
return err
}
return nil
}
func (tx *Base) Get(s storage.Storable, db *storage.DB) (storage.Storable, error) {
err := db.Get(s)
if err != nil {
return s, err
}
// to avoid race conditions, we block the call if there is
// already an active transaction by loop until InTransaction is false
ticker := time.NewTicker(time.Second * 10)
for tx.InTransaction {
select {
case <-ticker.C:
return nil, fmt.Errorf("transaction timeout")
default:
time.Sleep(time.Duration(500) * time.Millisecond)
err = db.Get(s)
}
}
if err != nil {
return nil, fmt.Errorf("could not get transaction")
}
return s, nil
}
func (tx *Base) Set(s storage.Storable, db *storage.DB) error {
tx.UpdatedAt = time.Now()
return db.Set(s)
}
+27
View File
@@ -0,0 +1,27 @@
package str
import (
"fmt"
"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
}
+73
View File
@@ -0,0 +1,73 @@
package telegram
import (
"errors"
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/price"
log "github.com/sirupsen/logrus"
)
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(strings.Split(input, " ")[1])
return amount, err
}
func getAmount(input string) (amount int, err error) {
// convert something like 1.2k into 1200
if strings.HasSuffix(strings.ToLower(input), "k") {
fmount, err := strconv.ParseFloat(strings.TrimSpace(input[:len(input)-1]), 64)
if err != nil {
return 0, err
}
amount = int(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 = int(fmount / price.Price[currency] * float64(100_000_000))
return amount, nil
}
}
// use plain integer as satoshis
amount, err = strconv.Atoi(input)
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
}
+13 -12
View File
@@ -1,6 +1,7 @@
package main
package telegram
import (
"context"
"fmt"
log "github.com/sirupsen/logrus"
@@ -8,34 +9,34 @@ import (
tb "gopkg.in/tucnak/telebot.v2"
)
func (bot TipBot) balanceHandler(m *tb.Message) {
func (bot TipBot) balanceHandler(ctx context.Context, m *tb.Message) {
// check and print all commands
bot.anyTextHandler(m)
bot.anyTextHandler(ctx, m)
// reply only in private message
if m.Chat.Type != tb.ChatPrivate {
// delete message
NewMessage(m).Dispose(0, bot.telegram)
NewMessage(m, WithDuration(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)
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
if !fromUser.Initialized {
bot.startHandler(m)
if !user.Initialized {
bot.startHandler(ctx, m)
return
}
usrStr := GetUserStr(m.Sender)
balance, err := bot.GetUserBalance(m.Sender)
balance, err := bot.GetUserBalance(user)
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.")
bot.trySendMessage(m.Sender, Translate(ctx, "balanceErrorMessage"))
return
}
log.Infof("[/balance] %s's balance: %d sat\n", usrStr, balance)
bot.telegram.Send(m.Sender, fmt.Sprintf("👑 *Your balance:* %d sat", balance))
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "balanceMessage"), balance))
return
}
+79
View File
@@ -0,0 +1,79 @@
package telegram
import (
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"sync"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
log "github.com/sirupsen/logrus"
"gopkg.in/tucnak/telebot.v2"
tb "gopkg.in/tucnak/telebot.v2"
"gorm.io/gorm"
)
type TipBot struct {
Database *gorm.DB
Bunt *storage.DB
logger *gorm.DB
Telegram *telebot.Bot
Client *lnbits.Client
}
var (
botWalletInitialisation = sync.Once{}
telegramHandlerRegistration = sync.Once{}
)
// NewBot migrates data and creates a new bot
func NewBot() TipBot {
// create sqlite databases
db, txLogger := migration()
return TipBot{
Database: db,
Client: lnbits.NewClient(internal.Configuration.Lnbits.AdminKey, internal.Configuration.Lnbits.Url),
logger: txLogger,
Bunt: createBunt(),
Telegram: newTelegramBot(),
}
}
// 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()
bot.Telegram.Start()
}
+120
View File
@@ -0,0 +1,120 @@
package telegram
import (
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/tidwall/buntdb"
"reflect"
"strconv"
"strings"
"time"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
tb "gopkg.in/tucnak/telebot.v2"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
const (
MessageOrderedByReplyToFrom = "message.reply_to_message.from.id"
TipTooltipKeyPattern = "tip-tool-tip:*"
)
func createBunt() *storage.DB {
// create bunt database
bunt := storage.NewBunt(internal.Configuration.Database.BuntDbPath)
// create bunt database index for ascending (searching) TipTooltips
err := bunt.CreateIndex(MessageOrderedByReplyToFrom, TipTooltipKeyPattern, buntdb.IndexJSON(MessageOrderedByReplyToFrom))
if err != nil {
panic(err)
}
return bunt
}
func migration() (db *gorm.DB, txLogger *gorm.DB) {
txLogger, err := gorm.Open(sqlite.Open(internal.Configuration.Database.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
if err != nil {
panic("Initialize orm failed.")
}
orm, err := gorm.Open(sqlite.Open(internal.Configuration.Database.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
}
func GetUserByTelegramUsername(toUserStrWithoutAt string, bot TipBot) (*lnbits.User, error) {
toUserDb := &lnbits.User{}
tx := bot.Database.Where("telegram_username = ?", strings.ToLower(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
}
// 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.Itoa(u.ID)}
tx := bot.Database.First(user)
if tx.Error != nil {
errmsg := fmt.Sprintf("[GetUser] Couldn't fetch %s from Database: %s", GetUserStr(u), tx.Error.Error())
log.Warnln(errmsg)
user.Telegram = u
return user, tx.Error
}
return user, nil
}
// GetUser from Telegram user. Update the user if user information changed.
func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
user, err := GetLnbitsUser(u, bot)
if err != nil {
return user, err
}
go func() {
userCopy := bot.copyLowercaseUser(u)
if !reflect.DeepEqual(userCopy, user.Telegram) {
// update possibly changed user details in Database
user.Telegram = userCopy
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 {
user.Telegram = bot.copyLowercaseUser(user.Telegram)
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))
return nil
}
+35 -45
View File
@@ -1,7 +1,9 @@
package main
package telegram
import (
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"io"
"io/ioutil"
"net/http"
@@ -18,40 +20,23 @@ import (
// IF YOU USE THIS PROJECT, LEAVE THIS CODE ALONE
var (
donationSuccess = "🙏 Thank you for your donation."
donationErrorMessage = "🚫 Oh no. Donation failed."
donationFailedMessage = "🚫 Donation failed: %s"
donateEnterAmountMessage = "Did you enter an amount?"
donateValidAmountMessage = "Did you enter a valid amount?"
donateHelpText = "📖 Oops, that didn't work. %s\n\n" +
"*Usage:* `/donate <amount>`\n" +
"*Example:* `/donate 1000`"
endpoint string
donationEndpoint string
)
func init() {
var sb strings.Builder
_, err := io.Copy(&sb, rot13Reader{strings.NewReader("uggcf://ya.gvcf/qbangr/%q?sebz=%f&obg=%f")})
if err != nil {
panic(err)
}
endpoint = sb.String()
}
func helpDonateUsage(errormsg string) string {
func helpDonateUsage(ctx context.Context, errormsg string) string {
if len(errormsg) > 0 {
return fmt.Sprintf(donateHelpText, fmt.Sprintf("%s", errormsg))
return fmt.Sprintf(Translate(ctx, "donateHelpText"), fmt.Sprintf("%s", errormsg))
} else {
return fmt.Sprintf(donateHelpText, "")
return fmt.Sprintf(Translate(ctx, "donateHelpText"), "")
}
}
func (bot TipBot) donationHandler(m *tb.Message) {
func (bot TipBot) donationHandler(ctx context.Context, m *tb.Message) {
// check and print all commands
bot.anyTextHandler(m)
bot.anyTextHandler(ctx, m)
if len(strings.Split(m.Text, " ")) < 2 {
bot.telegram.Send(m.Sender, helpDonateUsage(donateEnterAmountMessage))
bot.trySendMessage(m.Sender, helpDonateUsage(ctx, Translate(ctx, "donateEnterAmountMessage")))
return
}
amount, err := decodeAmountFromCommand(m.Text)
@@ -59,45 +44,50 @@ func (bot TipBot) donationHandler(m *tb.Message) {
return
}
if amount < 1 {
bot.telegram.Send(m.Sender, helpDonateUsage(donateValidAmountMessage))
bot.trySendMessage(m.Sender, helpDonateUsage(ctx, Translate(ctx, "donateValidAmountMessage")))
return
}
// command is valid
msg := bot.trySendMessage(m.Sender, Translate(ctx, "donationProgressMessage"))
// get invoice
resp, err := http.Get(fmt.Sprintf(endpoint, amount, GetUserStr(m.Sender), GetUserStr(bot.telegram.Me)))
resp, err := http.Get(fmt.Sprintf(donationEndpoint, amount, GetUserStr(m.Sender), GetUserStr(bot.Telegram.Me)))
if err != nil {
log.Errorln(err)
bot.telegram.Send(m.Sender, donationErrorMessage)
bot.tryEditMessage(msg, Translate(ctx, "donationErrorMessage"))
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorln(err)
bot.telegram.Send(m.Sender, donationErrorMessage)
bot.tryEditMessage(msg, Translate(ctx, "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)
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(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))
bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "donationFailedMessage"), err))
return
}
bot.telegram.Send(m.Sender, donationSuccess)
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()
}
type rot13Reader struct {
r io.Reader
}
@@ -123,17 +113,17 @@ func (rot13 rot13Reader) Read(b []byte) (int, error) {
return n, err
}
func (bot TipBot) parseCmdDonHandler(m *tb.Message) error {
func (bot TipBot) parseCmdDonHandler(ctx context.Context, m *tb.Message) error {
arg := ""
if strings.HasPrefix(strings.ToLower(m.Text), "/send") {
arg, _ = getArgumentFromCommand(m.Text, 2)
if arg != "@"+bot.telegram.Me.Username {
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")
}
}
@@ -147,15 +137,15 @@ func (bot TipBot) parseCmdDonHandler(m *tb.Message) error {
}
var sb strings.Builder
_, err = io.Copy(&sb, rot13Reader{strings.NewReader("Vg ybbxf yvxr lbh'er znxvat n qbangvba. V'z ebhgvat guvf gb gur bevtvany cebwrpg.")})
_, err = io.Copy(&sb, rot13Reader{strings.NewReader("Gunax lbh! V'z ebhgvat guvf qbangvba gb YvtugavatGvcObg@ya.gvcf.")})
if err != nil {
panic(err)
}
donationInterceptMessage := sb.String()
bot.telegram.Send(m.Sender, donationInterceptMessage)
bot.trySendMessage(m.Sender, str.MarkdownEscape(donationInterceptMessage))
m.Text = fmt.Sprintf("/donate %d", amount)
bot.donationHandler(m)
bot.donationHandler(ctx, m)
// returning nil here will abort the parent handler (/pay or /tip)
return nil
}
+319
View File
@@ -0,0 +1,319 @@
package telegram
import (
"context"
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
tb "gopkg.in/tucnak/telebot.v2"
)
type Handler struct {
Endpoints []interface{}
Handler interface{}
Interceptor *Interceptor
}
// registerTelegramHandlers will register all Telegram handlers.
func (bot TipBot) registerTelegramHandlers() {
telegramHandlerRegistration.Do(func() {
// Set up handlers
for _, h := range bot.getHandler() {
fmt.Println("registering", h.Endpoints)
bot.register(h)
}
})
}
// registerHandlerWithInterceptor will register a handler with all the predefined interceptors, based on the interceptor type
func (bot TipBot) registerHandlerWithInterceptor(h Handler) {
switch h.Interceptor.Type {
case MessageInterceptor:
h.Interceptor.Before = append(h.Interceptor.Before, bot.localizerInterceptor)
for _, endpoint := range h.Endpoints {
bot.handle(endpoint, intercept.HandlerWithMessage(h.Handler.(func(ctx context.Context, query *tb.Message)),
intercept.WithBeforeMessage(h.Interceptor.Before...),
intercept.WithAfterMessage(h.Interceptor.After...)))
}
case QueryInterceptor:
h.Interceptor.Before = append(h.Interceptor.Before, bot.localizerInterceptor)
for _, endpoint := range h.Endpoints {
bot.handle(endpoint, intercept.HandlerWithQuery(h.Handler.(func(ctx context.Context, query *tb.Query)),
intercept.WithBeforeQuery(h.Interceptor.Before...),
intercept.WithAfterQuery(h.Interceptor.After...)))
}
case CallbackInterceptor:
h.Interceptor.Before = append(h.Interceptor.Before, bot.localizerInterceptor)
for _, endpoint := range h.Endpoints {
bot.handle(endpoint, intercept.HandlerWithCallback(h.Handler.(func(ctx context.Context, callback *tb.Callback)),
intercept.WithBeforeCallback(h.Interceptor.Before...),
intercept.WithAfterCallback(h.Interceptor.After...)))
}
}
}
// handle accepts an endpoint and handler for Telegram handler registration.
// function will automatically register string handlers as uppercase and first letter uppercase.
func (bot TipBot) handle(endpoint interface{}, handler interface{}) {
// register the endpoint
bot.Telegram.Handle(endpoint, handler)
switch endpoint.(type) {
case string:
// check if this is a string endpoint
sEndpoint := endpoint.(string)
if strings.HasPrefix(sEndpoint, "/") {
// Uppercase endpoint registration, because starting with slash
bot.Telegram.Handle(strings.ToUpper(sEndpoint), handler)
if len(sEndpoint) > 2 {
// Also register endpoint with first letter uppercase
bot.Telegram.Handle(fmt.Sprintf("/%s%s", strings.ToUpper(string(sEndpoint[1])), sEndpoint[2:]), handler)
}
}
}
}
// register registers a handler, so that Telegram can handle the endpoint correctly.
func (bot TipBot) register(h Handler) {
if h.Interceptor != nil {
bot.registerHandlerWithInterceptor(h)
} else {
for _, endpoint := range h.Endpoints {
bot.handle(endpoint, h.Handler)
}
}
}
// getHandler returns a list of all handlers, that need to be registered with Telegram
func (bot TipBot) getHandler() []Handler {
return []Handler{
{
Endpoints: []interface{}{"/start"},
Handler: bot.startHandler,
Interceptor: &Interceptor{Type: MessageInterceptor},
},
{
Endpoints: []interface{}{"/faucet", "/zapfhahn", "/kraan", "/grifo"},
Handler: bot.faucetHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{bot.requireUserInterceptor}},
},
{
Endpoints: []interface{}{"/tip"},
Handler: bot.tipHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{
bot.logMessageInterceptor,
bot.loadUserInterceptor,
bot.loadReplyToInterceptor,
}},
},
{
Endpoints: []interface{}{"/pay"},
Handler: bot.payHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{
bot.logMessageInterceptor,
bot.loadUserInterceptor,
}},
},
{
Endpoints: []interface{}{"/invoice"},
Handler: bot.invoiceHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{
bot.logMessageInterceptor,
bot.loadUserInterceptor,
}},
},
{
Endpoints: []interface{}{"/balance"},
Handler: bot.balanceHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{
bot.logMessageInterceptor,
bot.loadUserInterceptor,
}},
},
{
Endpoints: []interface{}{"/send"},
Handler: bot.sendHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{
bot.logMessageInterceptor,
bot.loadUserInterceptor,
bot.loadReplyToInterceptor,
}},
},
{
Endpoints: []interface{}{"/help"},
Handler: bot.helpHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{
bot.logMessageInterceptor,
bot.loadUserInterceptor,
}},
},
{
Endpoints: []interface{}{"/basics"},
Handler: bot.basicsHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{
bot.logMessageInterceptor,
bot.loadUserInterceptor,
}},
},
{
Endpoints: []interface{}{"/donate"},
Handler: bot.donationHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{
bot.logMessageInterceptor,
bot.loadUserInterceptor,
}},
},
{
Endpoints: []interface{}{"/advanced"},
Handler: bot.advancedHelpHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{
bot.logMessageInterceptor,
bot.loadUserInterceptor,
}},
},
{
Endpoints: []interface{}{"/link"},
Handler: bot.lndhubHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{
bot.logMessageInterceptor,
bot.loadUserInterceptor}},
},
{
Endpoints: []interface{}{"/lnurl"},
Handler: bot.lnurlHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{
bot.logMessageInterceptor,
bot.loadUserInterceptor}},
},
{
Endpoints: []interface{}{tb.OnPhoto},
Handler: bot.photoHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.logMessageInterceptor,
bot.loadUserInterceptor}},
},
{
Endpoints: []interface{}{tb.OnText},
Handler: bot.anyTextHandler,
Interceptor: &Interceptor{
Type: MessageInterceptor,
Before: []intercept.Func{
bot.requirePrivateChatInterceptor,
bot.logMessageInterceptor, // Log message only if private chat
bot.loadUserInterceptor,
}},
},
{
Endpoints: []interface{}{tb.OnQuery},
Handler: bot.anyQueryHandler,
Interceptor: &Interceptor{
Type: QueryInterceptor,
Before: []intercept.Func{
bot.requireUserInterceptor,
bot.localizerInterceptor,
}},
},
{
Endpoints: []interface{}{tb.OnChosenInlineResult},
Handler: bot.anyChosenInlineHandler,
},
{
Endpoints: []interface{}{&btnPay},
Handler: bot.confirmPayHandler,
Interceptor: &Interceptor{
Type: CallbackInterceptor,
Before: []intercept.Func{bot.loadUserInterceptor}},
},
{
Endpoints: []interface{}{&btnCancelPay},
Handler: bot.cancelPaymentHandler,
Interceptor: &Interceptor{
Type: CallbackInterceptor,
Before: []intercept.Func{bot.loadUserInterceptor}},
},
{
Endpoints: []interface{}{&btnSend},
Handler: bot.confirmSendHandler,
Interceptor: &Interceptor{
Type: CallbackInterceptor,
Before: []intercept.Func{bot.loadUserInterceptor}},
},
{
Endpoints: []interface{}{&btnCancelSend},
Handler: bot.cancelSendHandler,
Interceptor: &Interceptor{
Type: CallbackInterceptor,
Before: []intercept.Func{bot.loadUserInterceptor}},
},
{
Endpoints: []interface{}{&btnAcceptInlineSend},
Handler: bot.acceptInlineSendHandler,
Interceptor: &Interceptor{
Type: CallbackInterceptor,
Before: []intercept.Func{bot.loadUserInterceptor}},
},
{
Endpoints: []interface{}{&btnCancelInlineSend},
Handler: bot.cancelInlineSendHandler,
Interceptor: &Interceptor{
Type: CallbackInterceptor,
Before: []intercept.Func{bot.loadUserInterceptor}},
},
{
Endpoints: []interface{}{&btnAcceptInlineReceive},
Handler: bot.acceptInlineReceiveHandler,
Interceptor: &Interceptor{
Type: CallbackInterceptor,
Before: []intercept.Func{bot.loadUserInterceptor}},
},
{
Endpoints: []interface{}{&btnCancelInlineReceive},
Handler: bot.cancelInlineReceiveHandler,
Interceptor: &Interceptor{
Type: CallbackInterceptor,
Before: []intercept.Func{bot.loadUserInterceptor}},
},
{
Endpoints: []interface{}{&btnAcceptInlineFaucet},
Handler: bot.acceptInlineFaucetHandler,
Interceptor: &Interceptor{
Type: CallbackInterceptor,
Before: []intercept.Func{bot.loadUserInterceptor}},
},
{
Endpoints: []interface{}{&btnCancelInlineFaucet},
Handler: bot.cancelInlineFaucetHandler,
Interceptor: &Interceptor{
Type: CallbackInterceptor,
Before: []intercept.Func{bot.loadUserInterceptor}},
},
}
}
+87
View File
@@ -0,0 +1,87 @@
package telegram
import (
"context"
"fmt"
tb "gopkg.in/tucnak/telebot.v2"
)
func (bot TipBot) makeHelpMessage(ctx context.Context, m *tb.Message) string {
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(m.Sender)
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
NewMessage(m, WithDuration(0, bot.Telegram))
}
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
NewMessage(m, WithDuration(0, bot.Telegram))
}
bot.trySendMessage(m.Sender, Translate(ctx, "basicsMessage"), tb.NoPreview)
return
}
func (bot TipBot) makeAdvancedHelpMessage(ctx context.Context, m *tb.Message) string {
dynamicHelpMessage := ""
// 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"))
} else {
dynamicHelpMessage = "ℹ️ *Info*\n"
lnaddr, err := bot.UserGetLightningAddress(m.Sender)
if err != nil {
dynamicHelpMessage = ""
} else {
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Your Lightning Address:\n`%s`\n", lnaddr)
}
lnurl, err := UserGetLNURL(m.Sender)
if err != nil {
dynamicHelpMessage = ""
} else {
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Your LNURL:\n`%s`", lnurl)
}
}
// this is so stupid:
return fmt.Sprintf(Translate(ctx, "advancedMessage"), dynamicHelpMessage, GetUserStr(bot.Telegram.Me), GetUserStr(bot.Telegram.Me), 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
NewMessage(m, WithDuration(0, bot.Telegram))
}
bot.trySendMessage(m.Sender, bot.makeAdvancedHelpMessage(ctx, m), tb.NoPreview)
return
}
+43
View File
@@ -0,0 +1,43 @@
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 int, total int) 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
}
+421
View File
@@ -0,0 +1,421 @@
package telegram
import (
"context"
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
)
var (
inlineFaucetMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
btnCancelInlineFaucet = inlineFaucetMenu.Data("🚫 Cancel", "cancel_faucet_inline")
btnAcceptInlineFaucet = inlineFaucetMenu.Data("✅ Collect", "confirm_faucet_inline")
)
type InlineFaucet struct {
*transaction.Base
Message string `json:"inline_faucet_message"`
Amount int `json:"inline_faucet_amount"`
RemainingAmount int `json:"inline_faucet_remainingamount"`
PerUserAmount int `json:"inline_faucet_peruseramount"`
From *lnbits.User `json:"inline_faucet_from"`
To []*tb.User `json:"inline_faucet_to"`
Memo string `json:"inline_faucet_memo"`
NTotal int `json:"inline_faucet_ntotal"`
NTaken int `json:"inline_faucet_ntaken"`
UserNeedsWallet bool `json:"inline_faucet_userneedswallet"`
LanguageCode string `json:"languagecode"`
}
func (bot TipBot) mapFaucetLanguage(ctx context.Context, command string) context.Context {
if len(strings.Split(command, " ")) > 1 {
c := strings.Split(command, " ")[0][1:] // cut the /
ctx = bot.commandTranslationMap(ctx, c)
}
return ctx
}
func (bot TipBot) createFaucet(ctx context.Context, text string, sender *tb.User) (*InlineFaucet, error) {
amount, err := decodeAmountFromCommand(text)
if err != nil {
return nil, errors.New(errors.DecodeAmountError, err)
}
peruserStr, err := getArgumentFromCommand(text, 2)
if err != nil {
return nil, errors.New(errors.DecodePerUserAmountError, err)
}
perUserAmount, err := getAmount(peruserStr)
if err != nil {
return nil, errors.New(errors.InvalidAmountError, err)
}
if perUserAmount < 1 || amount%perUserAmount != 0 {
return nil, errors.New(errors.InvalidAmountPerUserError, fmt.Errorf("invalid amount per user"))
}
nTotal := amount / perUserAmount
fromUser := LoadUser(ctx)
fromUserStr := GetUserStr(sender)
balance, err := bot.GetUserBalance(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: %v", fromUserStr, err))
}
// // 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("inl-faucet-%d-%d-%s", sender.ID, amount, RandStringRunes(5))
return &InlineFaucet{
Base: transaction.New(transaction.ID(id)),
Message: inlineMessage,
Amount: amount,
From: fromUser,
Memo: memo,
PerUserAmount: perUserAmount,
NTotal: nTotal,
NTaken: 0,
RemainingAmount: amount,
UserNeedsWallet: false,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}, nil
}
func (bot TipBot) makeFaucet(ctx context.Context, m *tb.Message, query bool) (*InlineFaucet, error) {
faucet, err := bot.createFaucet(ctx, m.Text, m.Sender)
if err != nil {
switch err.(errors.TipBotError).Code {
case errors.DecodeAmountError:
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidAmountMessage")))
bot.tryDeleteMessage(m)
return nil, err
case errors.DecodePerUserAmountError:
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), ""))
bot.tryDeleteMessage(m)
return nil, err
case errors.InvalidAmountError:
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidAmountMessage")))
bot.tryDeleteMessage(m)
return nil, err
case errors.InvalidAmountPerUserError:
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetInvalidPeruserAmountMessage")))
bot.tryDeleteMessage(m)
return nil, err
case errors.GetBalanceError:
// log.Errorln(err.Error())
bot.tryDeleteMessage(m)
return nil, err
case errors.BalanceToLowError:
// log.Errorf(err.Error())
bot.trySendMessage(m.Sender, Translate(ctx, "inlineSendBalanceLowMessage"))
bot.tryDeleteMessage(m)
return nil, err
}
}
return faucet, err
}
func (bot TipBot) makeQueryFaucet(ctx context.Context, q *tb.Query, query bool) (*InlineFaucet, error) {
faucet, err := bot.createFaucet(ctx, q.Text, &q.From)
if err != nil {
switch err.(errors.TipBotError).Code {
case errors.DecodeAmountError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.DecodePerUserAmountError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.InvalidAmountError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.InvalidAmountPerUserError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineFaucetInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.GetBalanceError:
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
case errors.BalanceToLowError:
log.Errorf(err.Error())
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendBalanceLowMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.Telegram.Me.Username))
return nil, err
}
}
return faucet, err
}
func (bot TipBot) makeFaucetKeyboard(ctx context.Context, id string) *tb.ReplyMarkup {
// inlineFaucetMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
acceptInlineFaucetButton := inlineFaucetMenu.Data(Translate(ctx, "collectButtonMessage"), "confirm_faucet_inline")
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) faucetHandler(ctx context.Context, m *tb.Message) {
bot.anyTextHandler(ctx, m)
if m.Private() {
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "inlineFaucetHelpText"), Translate(ctx, "inlineFaucetHelpFaucetInGroup")))
return
}
ctx = bot.mapFaucetLanguage(ctx, m.Text)
inlineFaucet, err := bot.makeFaucet(ctx, m, false)
if err != nil {
log.Errorf("[faucet] %s", err)
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) handleInlineFaucetQuery(ctx context.Context, q *tb.Query) {
inlineFaucet, err := bot.makeQueryFaucet(ctx, q, false)
if err != nil {
// log.Errorf("[faucet] %s", err)
return
}
/**amount, err := decodeAmountFromCommand(q.Text)
if err != nil {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.telegram.Me.Username))
return
}
if amount < 1 {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineSendInvalidAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.telegram.Me.Username))
return
}
peruserStr, err := getArgumentFromCommand(q.Text, 2)
if err != nil {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.telegram.Me.Username))
return
}
perUserAmount, err := getAmount(peruserStr)
if err != nil {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineQueryFaucetTitle"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.telegram.Me.Username))
return
}
// peruser amount must be >1 and a divisor of amount
if perUserAmount < 1 || amount%perUserAmount != 0 {
bot.inlineQueryReplyWithError(q, TranslateUser(ctx, "inlineFaucetInvalidPeruserAmountMessage"), fmt.Sprintf(TranslateUser(ctx, "inlineQueryFaucetDescription"), bot.telegram.Me.Username))
return
}
nTotal := amount / perUserAmount
fromUser := LoadUser(ctx)
fromUserStr := GetUserStr(&q.From)
balance, err := bot.GetUserBalance(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, "inlineQueryFaucetDescription"), bot.telegram.Me.Username))
return
}
// check for memo in command
memo := GetMemoFromCommand(q.Text, 3)
**/
// faucet, err := bot.createFaucet(ctx, q.Text, &q.From)
// if err != nil {
// log.Errorf(err.Error())
// return
// }
urls := []string{
queryImage,
}
results := make(tb.Results, len(urls)) // []tb.Result
for i, url := range urls {
// inlineMessage := fmt.Sprintf(Translate(ctx, "inlineFaucetMessage"), faucet.PerUserAmount, faucet.Amount, faucet.Amount, 0, faucet.NTotal, MakeProgressbar(faucet.Amount, faucet.Amount))
// if len(faucet.Memo) > 0 {
// inlineMessage = inlineMessage + fmt.Sprintf(Translate(ctx, "inlineFaucetAppendMemo"), faucet.Memo)
// }
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,
}
// id := fmt.Sprintf("inl-faucet-%d-%d-%s", q.From.ID, faucet.Amount, RandStringRunes(5))
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)
// create persistend inline send struct
// inlineFaucet := InlineFaucet{
// Base: transaction.New(transaction.ID(id)),
// Message: inlineMessage,
// From: faucet.From,
// Memo: faucet.Memo,
// NTaken: 0,
// Amount: faucet.Amount,
// PerUserAmount: faucet.PerUserAmount,
// RemainingAmount: faucet.Amount,
// UserNeedsWallet: false,
// LanguageCode: ctx.Value("publicLanguageCode").(string),
// }
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
log.Infof("[faucet] %s created inline faucet %s: %d sat (%d per user)", GetUserStr(inlineFaucet.From.Telegram), inlineFaucet.ID, inlineFaucet.Amount, inlineFaucet.PerUserAmount)
}
err = bot.Telegram.Answer(q, &tb.QueryResponse{
Results: results,
CacheTime: 1,
})
if err != nil {
log.Errorln(err)
}
}
func (bot *TipBot) acceptInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
to := LoadUser(ctx)
tx := &InlineFaucet{Base: transaction.New(transaction.ID(c.Data))}
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[faucet] %s", err)
return
}
inlineFaucet := fn.(*InlineFaucet)
from := inlineFaucet.From
err = inlineFaucet.Lock(inlineFaucet, bot.Bunt)
if err != nil {
log.Errorf("[faucet] LockFaucet %s error: %s", inlineFaucet.ID, err)
return
}
if !inlineFaucet.Active {
log.Errorf(fmt.Sprintf("[faucet] faucet %s inactive.", inlineFaucet.ID))
return
}
// release faucet no matter what
defer inlineFaucet.Release(inlineFaucet, bot.Bunt)
if from.Telegram.ID == to.Telegram.ID {
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.ID == to.Telegram.ID {
// to user is already in To slice, has taken from facuet
log.Infof("[faucet] %s already took from faucet %s", GetUserStr(to.Telegram), inlineFaucet.ID)
return
}
}
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 {
log.Infof("[faucet] User %s has no wallet.", toUserStr)
to, err = bot.CreateWalletForTelegramUser(to.Telegram)
if err != nil {
errmsg := fmt.Errorf("[faucet] Error: Could not create wallet for %s", toUserStr)
log.Errorln(errmsg)
return
}
}
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)
log.Errorln(errMsg)
return
}
log.Infof("[faucet] faucet %s: %d sat from %s to %s ", inlineFaucet.ID, inlineFaucet.PerUserAmount, fromUserStr, toUserStr)
inlineFaucet.NTaken += 1
inlineFaucet.To = append(inlineFaucet.To, to.Telegram)
inlineFaucet.RemainingAmount = inlineFaucet.RemainingAmount - inlineFaucet.PerUserAmount
_, err = bot.Telegram.Send(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "inlineFaucetReceivedMessage"), fromUserStrMd, inlineFaucet.PerUserAmount))
_, err = bot.Telegram.Send(from.Telegram, fmt.Sprintf(i18n.Translate(from.Telegram.LanguageCode, "inlineFaucetSentMessage"), inlineFaucet.PerUserAmount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[faucet] Error: Send message to %s: %s", toUserStr, err)
log.Errorln(errmsg)
return
}
// build faucet message
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetMessage"), inlineFaucet.PerUserAmount, 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)
bot.tryEditMessage(c.Message, inlineFaucet.Message, bot.makeFaucetKeyboard(ctx, inlineFaucet.ID))
}
if inlineFaucet.RemainingAmount < inlineFaucet.PerUserAmount {
// faucet is depleted
inlineFaucet.Message = fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetEndedMessage"), inlineFaucet.Amount, inlineFaucet.NTaken)
if inlineFaucet.UserNeedsWallet {
inlineFaucet.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
}
bot.tryEditMessage(c.Message, inlineFaucet.Message)
inlineFaucet.Active = false
}
}
func (bot *TipBot) cancelInlineFaucetHandler(ctx context.Context, c *tb.Callback) {
tx := &InlineFaucet{Base: transaction.New(transaction.ID(c.Data))}
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[cancelInlineSendHandler] %s", err)
return
}
inlineFaucet := fn.(*InlineFaucet)
if c.Sender.ID == inlineFaucet.From.Telegram.ID {
bot.tryEditMessage(c.Message, i18n.Translate(inlineFaucet.LanguageCode, "inlineFaucetCancelledMessage"), &tb.ReplyMarkup{})
// set the inlineFaucet inactive
inlineFaucet.Active = false
inlineFaucet.InTransaction = false
runtime.IgnoreError(inlineFaucet.Set(inlineFaucet, bot.Bunt))
}
return
}
+137
View File
@@ -0,0 +1,137 @@
package telegram
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
i18n2 "github.com/nicksnyder/go-i18n/v2/i18n"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
)
const queryImage = "https://avatars.githubusercontent.com/u/88730856?v=4"
func (bot TipBot) inlineQueryInstructions(ctx context.Context, q *tb.Query) {
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),
},
}
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)
}
}
func (bot TipBot) anyChosenInlineHandler(q *tb.ChosenInlineResult) {
fmt.Printf(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":
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.handleInlineFaucetQuery(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)
}
}
+212
View File
@@ -0,0 +1,212 @@
package telegram
import (
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/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 {
*transaction.Base
Message string `json:"inline_receive_message"`
Amount int `json:"inline_receive_amount"`
From *lnbits.User `json:"inline_receive_from"`
To *lnbits.User `json:"inline_receive_to"`
Memo string
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(
acceptInlineReceiveButton,
cancelInlineReceiveButton),
)
return inlineReceiveMenu
}
func (bot TipBot) handleInlineReceiveQuery(ctx context.Context, q *tb.Query) {
from := 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
}
fromUserStr := GetUserStr(&q.From)
// check for memo in command
memo := GetMemoFromCommand(q.Text, 2)
urls := []string{
queryImage,
}
results := make(tb.Results, len(urls)) // []tb.Result
for i, url := range urls {
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineReceiveMessage"), fromUserStr, amount)
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: transaction.New(transaction.ID(id)),
Message: inlineMessage,
To: from,
Memo: memo,
Amount: amount,
From: from,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
}
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: transaction.New(transaction.ID(c.Data))}
rn, err := tx.Get(tx, bot.Bunt)
// immediatelly set intransaction to block duplicate calls
if err != nil {
log.Errorf("[getInlineReceive] %s", err)
return
}
inlineReceive := rn.(*InlineReceive)
err = inlineReceive.Lock(inlineReceive, bot.Bunt)
if err != nil {
log.Errorf("[acceptInlineReceiveHandler] %s", err)
return
}
if !inlineReceive.Active {
log.Errorf("[acceptInlineReceiveHandler] inline receive not active anymore")
return
}
defer inlineReceive.Release(inlineReceive, bot.Bunt)
// user `from` is the one who is SENDING
// user `to` is the one who is RECEIVING
from := LoadUser(ctx)
if from.Wallet == nil {
return
}
to := inlineReceive.To
toUserStrMd := GetUserStrMd(to.Telegram)
fromUserStrMd := GetUserStrMd(from.Telegram)
toUserStr := GetUserStr(to.Telegram)
fromUserStr := GetUserStr(from.Telegram)
if from.Telegram.ID == to.Telegram.ID {
bot.trySendMessage(from.Telegram, Translate(ctx, "sendYourselfMessage"))
return
}
// balance check of the user
balance, err := bot.GetUserBalance(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)
log.Errorln(errMsg)
bot.tryEditMessage(c.Message, i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveFailedMessage"), &tb.ReplyMarkup{})
return
}
log.Infof("[acceptInlineReceiveHandler] %d sat from %s to %s", inlineReceive.Amount, fromUserStr, toUserStr)
inlineReceive.Message = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendUpdateMessageAccept"), inlineReceive.Amount, fromUserStrMd, toUserStrMd))
memo := inlineReceive.Memo
if len(memo) > 0 {
inlineReceive.Message = inlineReceive.Message + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineReceiveAppendMemo"), memo)
}
if !to.Initialized {
inlineReceive.Message += "\n\n" + fmt.Sprintf(i18n.Translate(inlineReceive.LanguageCode, "inlineSendCreateWalletMessage"), GetUserStrMd(bot.Telegram.Me))
}
bot.tryEditMessage(c.Message, inlineReceive.Message, &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.Errorln(errmsg)
return
}
}
func (bot *TipBot) cancelInlineReceiveHandler(ctx context.Context, c *tb.Callback) {
tx := &InlineReceive{Base: transaction.New(transaction.ID(c.Data))}
rn, err := tx.Get(tx, bot.Bunt)
// immediatelly set intransaction to block duplicate calls
if err != nil {
log.Errorf("[cancelInlineReceiveHandler] %s", err)
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
inlineReceive.InTransaction = false
runtime.IgnoreError(inlineReceive.Set(inlineReceive, bot.Bunt))
}
return
}
+224
View File
@@ -0,0 +1,224 @@
package telegram
import (
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/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 {
*transaction.Base
Message string `json:"inline_send_message"`
Amount int `json:"inline_send_amount"`
From *lnbits.User `json:"inline_send_from"`
To *tb.User `json:"inline_send_to"`
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.GetUserBalance(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 for memo in command
memo := GetMemoFromCommand(q.Text, 2)
urls := []string{
queryImage,
}
results := make(tb.Results, len(urls)) // []tb.Result
for i, url := range urls {
inlineMessage := fmt.Sprintf(Translate(ctx, "inlineSendMessage"), fromUserStr, amount)
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: transaction.New(transaction.ID(id)),
Message: inlineMessage,
From: fromUser,
Memo: memo,
Amount: amount,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
// add result to persistent struct
runtime.IgnoreError(inlineSend.Set(inlineSend, bot.Bunt))
}
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: transaction.New(transaction.ID(c.Data))}
sn, err := tx.Get(tx, bot.Bunt)
// immediatelly set intransaction to block duplicate calls
if err != nil {
log.Errorf("[acceptInlineSendHandler] %s", err)
return
}
inlineSend := sn.(*InlineSend)
fromUser := inlineSend.From
// immediatelly set intransaction to block duplicate calls
err = inlineSend.Lock(inlineSend, bot.Bunt)
if err != nil {
log.Errorf("[getInlineSend] %s", err)
return
}
if !inlineSend.Active {
log.Errorf("[acceptInlineSendHandler] inline send not active anymore")
return
}
defer inlineSend.Release(inlineSend, bot.Bunt)
amount := inlineSend.Amount
inlineSend.To = to.Telegram
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)
log.Errorln(errMsg)
bot.tryEditMessage(c.Message, i18n.Translate(inlineSend.LanguageCode, "inlineSendFailedMessage"), &tb.ReplyMarkup{})
return
}
log.Infof("[sendInline] %d sat from %s to %s", amount, fromUserStr, toUserStr)
inlineSend.Message = fmt.Sprintf("%s", fmt.Sprintf(i18n.Translate(inlineSend.LanguageCode, "inlineSendUpdateMessageAccept"), amount, fromUserStrMd, toUserStrMd))
memo := inlineSend.Memo
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.Errorln(errmsg)
return
}
}
func (bot *TipBot) cancelInlineSendHandler(ctx context.Context, c *tb.Callback) {
tx := &InlineSend{Base: transaction.New(transaction.ID(c.Data))}
sn, err := tx.Get(tx, bot.Bunt)
// immediatelly set intransaction to block duplicate calls
if err != nil {
log.Errorf("[cancelInlineSendHandler] %s", err)
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
inlineSend.InTransaction = false
runtime.IgnoreError(inlineSend.Set(inlineSend, bot.Bunt))
}
return
}
+64
View File
@@ -0,0 +1,64 @@
package intercept
import (
"context"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/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
}
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 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, err := interceptCallback(context.Background(), c, hm.before)
if err != nil {
log.Traceln(err)
return
}
hm.handler(ctx, c)
_, err = interceptCallback(ctx, c, hm.after)
if err != nil {
log.Traceln(err)
}
}
}
+68
View File
@@ -0,0 +1,68 @@
package intercept
import (
"context"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/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
}
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 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, err := interceptMessage(context.Background(), message, hm.before)
if err != nil {
log.Traceln(err)
return
}
hm.handler(ctx, message)
_, err = interceptMessage(ctx, message, hm.after)
if err != nil {
log.Traceln(err)
return
}
}
}
+64
View File
@@ -0,0 +1,64 @@
package intercept
import (
"context"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
)
type QueryFuncHandler func(ctx context.Context, message *tb.Query)
type handlerQueryInterceptor struct {
handler QueryFuncHandler
before QueryChain
after 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 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(message *tb.Query) {
ctx, err := interceptQuery(context.Background(), message, hm.before)
if err != nil {
log.Traceln(err)
return
}
hm.handler(ctx, message)
_, err = interceptQuery(ctx, message, hm.after)
if err != nil {
log.Traceln(err)
return
}
}
}
+172
View File
@@ -0,0 +1,172 @@
package telegram
import (
"context"
"fmt"
"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/tucnak/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
}
func (bot TipBot) requireUserInterceptor(ctx context.Context, i interface{}) (context.Context, error) {
switch i.(type) {
case *tb.Query:
user, err := GetUser(&i.(*tb.Query).From, bot)
return context.WithValue(ctx, "user", user), err
case *tb.Callback:
c := i.(*tb.Callback)
m := *c.Message
m.Sender = c.Sender
user, err := GetUser(i.(*tb.Callback).Sender, bot)
return context.WithValue(ctx, "user", user), err
case *tb.Message:
user, err := GetUser(i.(*tb.Message).Sender, bot)
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
}
// 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("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.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
} 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
}
+20 -22
View File
@@ -1,8 +1,10 @@
package main
package telegram
import (
"bytes"
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"strings"
log "github.com/sirupsen/logrus"
@@ -12,36 +14,32 @@ import (
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 {
func helpInvoiceUsage(ctx context.Context, errormsg string) string {
if len(errormsg) > 0 {
return fmt.Sprintf(invoiceHelpText, fmt.Sprintf("%s", errormsg))
return fmt.Sprintf(Translate(ctx, "invoiceHelpText"), fmt.Sprintf("%s", errormsg))
} else {
return fmt.Sprintf(invoiceHelpText, "")
return fmt.Sprintf(Translate(ctx, "invoiceHelpText"), "")
}
}
func (bot TipBot) invoiceHandler(m *tb.Message) {
func (bot TipBot) invoiceHandler(ctx context.Context, m *tb.Message) {
// check and print all commands
bot.anyTextHandler(m)
bot.anyTextHandler(ctx, m)
if m.Chat.Type != tb.ChatPrivate {
// delete message
NewMessage(m).Dispose(0, bot.telegram)
NewMessage(m, WithDuration(0, bot.Telegram))
return
}
if len(strings.Split(m.Text, " ")) < 2 {
bot.telegram.Send(m.Sender, helpInvoiceUsage(invoiceEnterAmountMessage))
bot.trySendMessage(m.Sender, helpInvoiceUsage(ctx, Translate(ctx, "invoiceEnterAmountMessage")))
return
}
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
user, err := GetUser(m.Sender, bot)
userStr := GetUserStr(m.Sender)
amount, err := decodeAmountFromCommand(m.Text)
if err != nil {
@@ -49,14 +47,14 @@ func (bot TipBot) invoiceHandler(m *tb.Message) {
}
if amount > 0 {
} else {
bot.telegram.Send(m.Sender, helpInvoiceUsage(invoiceValidAmountMessage))
bot.trySendMessage(m.Sender, helpInvoiceUsage(ctx, Translate(ctx, "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]
memo = GetMemoFromCommand(m.Text, 2)
tag := " (@LightningTipBot)"
memoMaxLen := 159 - len(tag)
if len(memo) > memoMaxLen {
@@ -72,8 +70,8 @@ func (bot TipBot) invoiceHandler(m *tb.Message) {
Out: false,
Amount: int64(amount),
Memo: memo,
Webhook: Configuration.WebhookServer},
*user.Wallet)
Webhook: internal.Configuration.Lnbits.WebhookServer},
bot.Client)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Could not create an invoice: %s", err)
log.Errorln(errmsg)
@@ -89,7 +87,7 @@ func (bot TipBot) invoiceHandler(m *tb.Message) {
}
// 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)})
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
}
+42
View File
@@ -0,0 +1,42 @@
package telegram
import (
"bytes"
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
log "github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode"
tb "gopkg.in/tucnak/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
NewMessage(m, WithDuration(0, bot.Telegram))
}
// first check whether the user is initialized
fromUser := LoadUser(ctx)
bot.trySendMessage(m.Sender, Translate(ctx, "walletConnectMessage"))
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)
log.Errorln(errmsg)
return
}
// send the invoice data to user
bot.trySendMessage(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
}
+414
View File
@@ -0,0 +1,414 @@
package telegram
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
lnurl "github.com/fiatjaf/go-lnurl"
log "github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode"
"github.com/tidwall/gjson"
tb "gopkg.in/tucnak/telebot.v2"
)
// lnurlHandler is invoked on /lnurl command
func (bot TipBot) lnurlHandler(ctx context.Context, m *tb.Message) {
// commands:
// /lnurl
// /lnurl <LNURL>
// or /lnurl <amount> <LNURL>
log.Infof("[lnurlHandler] %s", m.Text)
// if only /lnurl is entered, show the lnurl of the user
if m.Text == "/lnurl" {
bot.lnurlReceiveHandler(ctx, m)
return
}
// assume payment
// HandleLNURL by fiatjaf/go-lnurl
msg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlResolvingUrlMessage"))
_, params, err := HandleLNURL(m.Text)
if err != nil {
bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), "could not resolve LNURL."))
log.Errorln(err)
return
}
var payParams LnurlStateResponse
switch params.(type) {
case lnurl.LNURLPayResponse1:
payParams = LnurlStateResponse{LNURLPayResponse1: params.(lnurl.LNURLPayResponse1)}
log.Infof("[lnurlHandler] %s", payParams.Callback)
default:
err := fmt.Errorf("invalid LNURL type.")
log.Errorln(err)
bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
// bot.trySendMessage(m.Sender, err.Error())
return
}
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 {
// set LNURLPayResponse1 in the state of the user
paramsJson, err := json.Marshal(payParams)
if err != nil {
log.Errorln(err)
return
}
SetUserState(user, bot, lnbits.UserStateLNURLEnterAmount, string(paramsJson))
bot.tryDeleteMessage(msg)
// Let the user enter an amount and return
bot.trySendMessage(m.Sender,
fmt.Sprintf(Translate(ctx, "lnurlEnterAmountMessage"), payParams.MinSendable/1000, payParams.MaxSendable/1000),
tb.ForceReply)
} else {
// amount is already present in the command
// amount not in allowed range from LNURL
// if int64(amount) > (payParams.MaxSendable/1000) || int64(amount) < (payParams.MinSendable/1000) {
// err = fmt.Errorf("amount not in range")
// log.Errorln(err)
// bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), payParams.MinSendable/1000, payParams.MaxSendable/1000))
// ResetUserState(user, bot)
// return
// }
// set also amount in the state of the user
payParams.Amount = amount
// check if comment is presentin lnrul-p
memo := GetMemoFromCommand(m.Text, 3)
// shorten comment to allowed length
if len(memo) > int(payParams.CommentAllowed) {
memo = memo[:payParams.CommentAllowed]
}
// save it
payParams.Comment = memo
paramsJson, err := json.Marshal(payParams)
if err != nil {
log.Errorln(err)
// bot.trySendMessage(m.Sender, err.Error())
return
}
SetUserState(user, bot, lnbits.UserStateConfirmLNURLPay, string(paramsJson))
bot.tryDeleteMessage(msg)
// directly go to confirm
bot.lnurlPayHandler(ctx, m)
}
}
func (bot *TipBot) UserGetLightningAddress(user *tb.User) (string, error) {
if len(user.Username) > 0 {
return fmt.Sprintf("%s@%s", strings.ToLower(user.Username), strings.ToLower(internal.Configuration.Bot.LNURLHostUrl.Hostname())), nil
} else {
return "", fmt.Errorf("user has no username")
}
}
func UserGetLNURL(user *tb.User) (string, error) {
name := strings.ToLower(strings.ToLower(user.Username))
if len(name) == 0 {
return "", fmt.Errorf("user has no username.")
}
callback := fmt.Sprintf("%s/.well-known/lnurlp/%s", internal.Configuration.Bot.LNURLHostName, name)
log.Debugf("[lnurlReceiveHandler] %s's LNURL: %s", GetUserStr(user), 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) {
lnurlEncode, err := UserGetLNURL(m.Sender)
if err != nil {
errmsg := fmt.Sprintf("[lnurlReceiveHandler] Failed to get LNURL: %s", err)
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("[lnurlReceiveHandler] Failed to create QR code for LNURL: %s", err)
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)})
}
// lnurlEnterAmountHandler is invoked if the user didn't deliver an amount for the lnurl payment
func (bot TipBot) lnurlEnterAmountHandler(ctx context.Context, m *tb.Message) {
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
if user.StateKey == lnbits.UserStateLNURLEnterAmount {
a, err := strconv.Atoi(m.Text)
if err != nil {
log.Errorln(err)
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
ResetUserState(user, bot)
return
}
amount := int64(a)
var stateResponse LnurlStateResponse
err = json.Unmarshal([]byte(user.StateData), &stateResponse)
if err != nil {
log.Errorln(err)
ResetUserState(user, bot)
return
}
// amount not in allowed range from LNURL
if amount > (stateResponse.MaxSendable/1000) || amount < (stateResponse.MinSendable/1000) {
err = fmt.Errorf("amount not in range")
log.Errorln(err)
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), stateResponse.MinSendable/1000, stateResponse.MaxSendable/1000))
ResetUserState(user, bot)
return
}
stateResponse.Amount = a
state, err := json.Marshal(stateResponse)
if err != nil {
log.Errorln(err)
ResetUserState(user, bot)
return
}
SetUserState(user, bot, lnbits.UserStateConfirmLNURLPay, string(state))
bot.lnurlPayHandler(ctx, m)
}
}
// LnurlStateResponse saves the state of the user for an LNURL payment
type LnurlStateResponse struct {
lnurl.LNURLPayResponse1
Amount int `json:"amount"`
Comment string `json:"comment"`
}
// lnurlPayHandler is invoked when the user has delivered an amount and is ready to pay
func (bot TipBot) lnurlPayHandler(ctx context.Context, c *tb.Message) {
msg := bot.trySendMessage(c.Sender, Translate(ctx, "lnurlGettingUserMessage"))
user := LoadUser(ctx)
if user.Wallet == nil {
return
}
if user.StateKey == lnbits.UserStateConfirmLNURLPay {
client, err := getHttpClient()
if err != nil {
log.Errorln(err)
// bot.trySendMessage(c.Sender, err.Error())
bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
return
}
var stateResponse LnurlStateResponse
err = json.Unmarshal([]byte(user.StateData), &stateResponse)
if err != nil {
log.Errorln(err)
// bot.trySendMessage(c.Sender, err.Error())
bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
return
}
callbackUrl, err := url.Parse(stateResponse.Callback)
if err != nil {
log.Errorln(err)
// bot.trySendMessage(c.Sender, err.Error())
bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
return
}
qs := callbackUrl.Query()
// add amount to query string
qs.Set("amount", strconv.Itoa(stateResponse.Amount*1000))
// add comment to query string
if len(stateResponse.Comment) > 0 {
qs.Set("comment", stateResponse.Comment)
}
callbackUrl.RawQuery = qs.Encode()
res, err := client.Get(callbackUrl.String())
if err != nil {
log.Errorln(err)
// bot.trySendMessage(c.Sender, err.Error())
bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
return
}
var response2 lnurl.LNURLPayResponse2
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Errorln(err)
// bot.trySendMessage(c.Sender, err.Error())
bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), err))
return
}
json.Unmarshal(body, &response2)
if len(response2.PR) < 1 {
bot.tryEditMessage(msg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), "could not receive invoice (wrong address?)."))
return
}
bot.Telegram.Delete(msg)
c.Text = fmt.Sprintf("/pay %s", response2.PR)
bot.payHandler(ctx, c)
}
}
func 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) {
}
// from https://github.com/fiatjaf/go-lnurl
func 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 {
foundUrl, ok := lnurl.FindLNURLInText(rawlnurl)
if !ok {
return "", nil,
errors.New("invalid bech32-encoded lnurl: " + rawlnurl)
}
rawurl, err = lnurl.LNURLDecode(foundUrl)
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
}
}
client, err := getHttpClient()
if err != nil {
return "", nil, err
}
resp, err := client.Get(rawurl)
if err != nil {
return rawurl, nil, err
}
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(j)
return rawurl, value, err
case "payRequest":
value, err := lnurl.HandlePay(j)
return rawurl, value, err
case "channelRequest":
value, err := lnurl.HandleChannel(j)
return rawurl, value, err
default:
return rawurl, nil, errors.New("unknown response tag " + j.String())
}
}
func (bot *TipBot) sendToLightningAddress(ctx context.Context, m *tb.Message, address string, amount int) 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
}
+53
View File
@@ -0,0 +1,53 @@
package telegram
import (
"strconv"
"time"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
)
type Message struct {
Message *tb.Message `json:"message"`
duration time.Duration
}
type MessageOption func(m *Message)
func WithDuration(duration time.Duration, bot *tb.Bot) MessageOption {
return func(m *Message) {
m.duration = duration
go m.dispose(bot)
}
}
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(telegram *tb.Bot) {
// do not delete messages from private chat
if msg.Message.Private() {
return
}
go func() {
time.Sleep(msg.duration)
err := telegram.Delete(msg.Message)
if err != nil {
log.Println(err.Error())
return
}
}()
}
+233
View File
@@ -0,0 +1,233 @@
package telegram
import (
"context"
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
"github.com/LightningTipBot/LightningTipBot/internal/str"
decodepay "github.com/fiatjaf/ln-decodepay"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/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 {
*transaction.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"`
}
// 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.Telegram))
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.Telegram))
bot.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "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.trySendMessage(m.Sender, helpPayInvoiceUsage(ctx, Translate(ctx, "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.trySendMessage(m.Sender, Translate(ctx, "invoiceNoAmountMessage"))
errmsg := fmt.Sprint("[/pay] Error: invoice without amount")
log.Errorln(errmsg)
return
}
// check user balance first
balance, err := bot.GetUserBalance(user)
if err != nil {
NewMessage(m, WithDuration(0, bot.Telegram))
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err)
log.Errorln(errmsg)
return
}
if amount > balance {
NewMessage(m, WithDuration(0, bot.Telegram))
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.Printf("[/pay] User: %s, amount: %d sat.", userStr, amount)
// object that holds all information about the send payment
id := fmt.Sprintf("pay-%d-%d-%s", m.Sender.ID, amount, RandStringRunes(5))
payData := PayData{
From: user,
Invoice: paymentRequest,
Base: transaction.New(transaction.ID(id)),
Amount: int64(amount),
Memo: bolt11.Description,
Message: confirmText,
LanguageCode: ctx.Value("publicLanguageCode").(string),
}
// add result to persistent struct
runtime.IgnoreError(payData.Set(payData, bot.Bunt))
SetUserState(user, bot, lnbits.UserStateConfirmPayment, paymentRequest)
// // // 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),
)
bot.trySendMessage(m.Chat, confirmText, paymentConfirmationMenu)
}
// confirmPayHandler when user clicked pay on payment confirmation
func (bot TipBot) confirmPayHandler(ctx context.Context, c *tb.Callback) {
tx := &PayData{Base: transaction.New(transaction.ID(c.Data))}
sn, err := tx.Get(tx, bot.Bunt)
// immediatelly set intransaction to block duplicate calls
if err != nil {
log.Errorf("[confirmPayHandler] %s", err)
return
}
payData := sn.(*PayData)
// onnly the correct user can press
if payData.From.Telegram.ID != c.Sender.ID {
return
}
// immediatelly set intransaction to block duplicate calls
err = payData.Lock(payData, bot.Bunt)
if err != nil {
log.Errorf("[acceptSendHandler] %s", err)
bot.tryDeleteMessage(c.Message)
return
}
if !payData.Active {
log.Errorf("[confirmPayHandler] send not active anymore")
bot.tryDeleteMessage(c.Message)
return
}
defer payData.Release(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)
// 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)
if len(err.Error()) == 0 {
err = fmt.Errorf(i18n.Translate(payData.LanguageCode, "invoiceUndefinedErrorMessage"))
}
// bot.trySendMessage(c.Sender, fmt.Sprintf(invoicePaymentFailedMessage, err))
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
payData.InTransaction = false
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.Printf("[pay] User %s paid invoice %s (%d sat)", userStr, payData.ID, payData.Amount)
return
}
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
func (bot TipBot) cancelPaymentHandler(ctx context.Context, c *tb.Callback) {
// reset state immediately
user := LoadUser(ctx)
ResetUserState(user, bot)
tx := &PayData{Base: transaction.New(transaction.ID(c.Data))}
sn, err := tx.Get(tx, bot.Bunt)
// immediatelly set intransaction to block duplicate calls
if err != nil {
log.Errorf("[cancelPaymentHandler] %s", err)
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.InTransaction = false
payData.Inactivate(payData, bot.Bunt)
}
+75
View File
@@ -0,0 +1,75 @@
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/tucnak/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
}
// 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)
return
}
// decode to jpeg image
img, err := jpeg.Decode(reader)
if err != nil {
log.Errorf("[photoHandler] image.Decode error: %v\n", err)
return
}
data, err := TryRecognizeQrCode(img)
if err != nil {
log.Errorf("[photoHandler] tryRecognizeQrCodes error: %v\n", err)
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
}
}
+302
View File
@@ -0,0 +1,302 @@
package telegram
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
"github.com/LightningTipBot/LightningTipBot/internal/storage/transaction"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/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 {
*transaction.Base
From *lnbits.User `json:"from"`
ToTelegramId int `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() {
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.Telegram))
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
}
}
// todo: this error might have been overwritten by the functions above
// we should only check for a valid amount here, instead of error and amount
// ASSUME INTERNAL SEND TO TELEGRAM USER
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, WithDuration(0, bot.Telegram))
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 plan 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
}
toUserStrMention = "@" + toUserStrWithoutAt
toUserStrWithoutAt = strings.TrimPrefix(toUserStrWithoutAt, "@")
}
err = bot.parseCmdDonHandler(ctx, m)
if err == nil {
return
}
toUserDb, err := GetUserByTelegramUsername(toUserStrWithoutAt, *bot)
if err != nil {
NewMessage(m, WithDuration(0, bot.Telegram))
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "sendUserHasNoWalletMessage"), toUserStrMention))
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: transaction.New(transaction.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.Telegram))
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: transaction.New(transaction.ID(c.Data))}
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[acceptSendHandler] %s", err)
return
}
sendData := sn.(*SendData)
// onnly the correct user can press
if sendData.From.Telegram.ID != c.Sender.ID {
return
}
// immediatelly set intransaction to block duplicate calls
err = sendData.Lock(sendData, bot.Bunt)
if err != nil {
log.Errorf("[acceptSendHandler] %s", err)
bot.tryDeleteMessage(c.Message)
return
}
if !sendData.Active {
log.Errorf("[acceptSendHandler] send not active anymore")
// bot.tryDeleteMessage(c.Message)
return
}
defer sendData.Release(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, int(amount), TransactionType("send"))
t.Memo = transactionMemo
success, err := t.Send()
if !success || err != nil {
// bot.trySendMessage(c.Sender, sendErrorMessage)
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err)
log.Errorln(errmsg)
bot.tryEditMessage(c.Message, fmt.Sprintf("%s %s", i18n.Translate(sendData.LanguageCode, "sendErrorMessage"), err), &tb.ReplyMarkup{})
return
}
sendData.Inactivate(sendData, bot.Bunt)
log.Infof("[send] Transaction sent from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
// notify to user
bot.trySendMessage(to.Telegram, fmt.Sprintf(i18n.Translate(to.Telegram.LanguageCode, "sendReceivedMessage"), fromUserStrMd, amount))
// bot.trySendMessage(from.Telegram, fmt.Sprintf(Translate(ctx, "sendSentMessage"), amount, toUserStrMd))
if c.Message.Private() {
// if the command was invoked in private chat
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: transaction.New(transaction.ID(c.Data))}
sn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[acceptSendHandler] %s", err)
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.InTransaction = false
sendData.Inactivate(sendData, bot.Bunt)
}
+30 -32
View File
@@ -1,9 +1,12 @@
package main
package telegram
import (
"context"
"errors"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"strconv"
"time"
log "github.com/sirupsen/logrus"
@@ -12,52 +15,47 @@ import (
"gorm.io/gorm"
)
const (
startSettingWalletMessage = "🧮 Setting up your wallet..."
startWalletReadyMessage = "✅ *Your wallet is ready.*"
startWalletErrorMessage = "🚫 Error initializing your wallet. Try again later."
startNoUsernameMessage = "☝️ It looks like you don't have a Telegram @username yet. That's ok, you don't need one to use this bot. However, to make better use of your wallet, set up a username in the [Telegram settings](https://telegram.org/faq#q-what-are-usernames-how-do-i-get-one). Then, enter /balance so the bot can update its record of you."
)
func (bot TipBot) startHandler(m *tb.Message) {
func (bot TipBot) startHandler(ctx context.Context, m *tb.Message) {
if !m.Private() {
return
}
// ATTENTION: DO NOT CALL ANY HANDLER BEFORE THE WALLET IS CREATED
// WILL RESULT IN AN ENDLESS LOOP OTHERWISE
// bot.helpHandler(m)
bot.telegram.Send(m.Sender, helpMessage, tb.NoPreview)
log.Printf("[/start] User: %s (%d)\n", m.Sender.Username, m.Sender.ID)
walletCreationMsg, err := bot.telegram.Send(m.Sender, startSettingWalletMessage)
err = bot.initWallet(m.Sender)
walletCreationMsg, err := bot.Telegram.Send(m.Sender, Translate(ctx, "startSettingWalletMessage"))
user, err := bot.initWallet(m.Sender)
if err != nil {
log.Errorln(fmt.Sprintf("[startHandler] Error with initWallet: %s", err.Error()))
bot.telegram.Edit(walletCreationMsg, startWalletErrorMessage)
bot.tryEditMessage(walletCreationMsg, Translate(ctx, "startWalletErrorMessage"))
return
}
bot.telegram.Edit(walletCreationMsg, startWalletReadyMessage)
bot.balanceHandler(m)
bot.tryDeleteMessage(walletCreationMsg)
ctx = context.WithValue(ctx, "user", user)
bot.helpHandler(ctx, m)
bot.trySendMessage(m.Sender, Translate(ctx, "startWalletReadyMessage"))
bot.balanceHandler(ctx, m)
// send the user a warning about the fact that they need to set a username
if len(m.Sender.Username) == 0 {
bot.telegram.Send(m.Sender, startNoUsernameMessage, tb.NoPreview)
bot.trySendMessage(m.Sender, Translate(ctx, "startNoUsernameMessage"), tb.NoPreview)
}
return
}
func (bot TipBot) initWallet(tguser *tb.User) error {
func (bot TipBot) initWallet(tguser *tb.User) (*lnbits.User, error) {
user, err := GetUser(tguser, bot)
if errors.Is(err, gorm.ErrRecordNotFound) {
u := &lnbits.User{Telegram: tguser}
err = bot.createWallet(u)
user = &lnbits.User{Telegram: tguser}
err = bot.createWallet(user)
if err != nil {
return err
return user, err
}
u.Initialized = true
err = UpdateUserRecord(u, bot)
user.Initialized = true
err = UpdateUserRecord(user, bot)
if err != nil {
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
return err
return user, err
}
} else if !user.Initialized {
// update all tip tooltips (with the "initialize me" message) that this user might have received before
@@ -66,41 +64,41 @@ func (bot TipBot) initWallet(tguser *tb.User) error {
err = UpdateUserRecord(user, bot)
if err != nil {
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
return err
return user, err
}
} else if user.Initialized {
// wallet is already initialized
return nil
return user, nil
} else {
err = fmt.Errorf("could not initialize wallet")
return err
return user, err
}
return nil
return user, nil
}
func (bot TipBot) createWallet(user *lnbits.User) error {
UserStr := GetUserStr(user.Telegram)
u, err := bot.client.CreateUserWithInitialWallet(strconv.Itoa(user.Telegram.ID),
u, err := bot.Client.CreateUserWithInitialWallet(strconv.Itoa(user.Telegram.ID),
fmt.Sprintf("%d (%s)", user.Telegram.ID, UserStr),
Configuration.AdminKey,
internal.Configuration.Lnbits.AdminId,
UserStr)
if err != nil {
errormsg := fmt.Sprintf("[createWallet] Create wallet error: %s", err)
log.Errorln(errormsg)
return err
}
user.Wallet = &lnbits.Wallet{Client: bot.client}
user.Wallet = &lnbits.Wallet{}
user.ID = u.ID
user.Name = u.Name
wallet, err := user.Wallet.Wallets(*user)
wallet, err := bot.Client.Wallets(*user)
if err != nil {
errormsg := fmt.Sprintf("[createWallet] Get wallet error: %s", err)
log.Errorln(errormsg)
return err
}
user.Wallet = &wallet[0]
user.Wallet.Client = bot.client
user.Initialized = false
user.CreatedAt = time.Now()
err = UpdateUserRecord(user, bot)
if err != nil {
errormsg := fmt.Sprintf("[createWallet] Update user record error: %s", err)
+44
View File
@@ -0,0 +1,44 @@
package telegram
import (
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
)
func (bot TipBot) tryForwardMessage(to tb.Recipient, what tb.Editable, options ...interface{}) (msg *tb.Message) {
msg, err := bot.Telegram.Forward(to, what, options...)
if err != nil {
log.Errorln(err.Error())
}
return
}
func (bot TipBot) trySendMessage(to tb.Recipient, what interface{}, options ...interface{}) (msg *tb.Message) {
msg, err := bot.Telegram.Send(to, what, options...)
if err != nil {
log.Errorln(err.Error())
}
return
}
func (bot TipBot) tryReplyMessage(to *tb.Message, what interface{}, options ...interface{}) (msg *tb.Message) {
msg, err := bot.Telegram.Reply(to, what, options...)
if err != nil {
log.Errorln(err.Error())
}
return
}
func (bot TipBot) tryEditMessage(to tb.Editable, what interface{}, options ...interface{}) (msg *tb.Message) {
msg, err := bot.Telegram.Edit(to, what, options...)
if err != nil {
log.Errorln(err.Error())
}
return
}
func (bot TipBot) tryDeleteMessage(msg tb.Editable) {
err := bot.Telegram.Delete(msg)
if err != nil {
log.Errorln(err.Error())
}
}
+43
View File
@@ -0,0 +1,43 @@
package telegram
import (
"context"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
tb "gopkg.in/tucnak/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
}
// could be a LNURL
// var lnurlregex = regexp.MustCompile(`.*?((lnurl)([0-9]{1,}[a-z0-9]+){1})`)
if user.StateKey == lnbits.UserStateLNURLEnterAmount {
bot.lnurlEnterAmountHandler(ctx, m)
}
}
+143
View File
@@ -0,0 +1,143 @@
package telegram
import (
"context"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/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) {
// delete the tip message after a few seconds, this is default behaviour
defer NewMessage(m, WithDuration(time.Second*time.Duration(internal.Configuration.Telegram.MessageDisposeDuration), bot.Telegram))
// 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() {
NewMessage(m, WithDuration(0, bot.Telegram))
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.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, WithDuration(0, bot.Telegram))
bot.trySendMessage(m.Sender, helpTipUsage(ctx, Translate(ctx, "tipValidAmountMessage")))
log.Errorln(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.Telegram))
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.Telegram))
bot.trySendMessage(m.Sender, Translate(ctx, "tipErrorMessage"))
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err)
log.Errorln(errMsg)
return
}
// update tooltip if necessary
messageHasTip := tipTooltipHandler(m, bot, amount, to.Initialized)
log.Infof("[tip] Transaction sent 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.Errorln(errmsg)
return
}
// 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)))
}
return
}
+196
View File
@@ -0,0 +1,196 @@
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/tucnak/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
TipAmount int `json:"tip_amount"`
Ntips int `json:"ntips"`
LastTip time.Time `json:"last_tip"`
Tippers []*tb.User `json:"tippers"`
}
const maxNamesInTipperMessage = 5
type TipTooltipOption func(m *TipTooltip)
func TipAmount(amount int) 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{
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(replyToId int, bot *TipBot) (bool, *TipTooltip) {
message := NewTipTooltip(&tb.Message{ReplyTo: &tb.Message{ID: replyToId}})
err := bot.Bunt.Get(message)
if err != nil {
return false, message
}
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 int, initializedWallet bool) (hasTip bool) {
// todo: this crashes if the tooltip message (maybe also the original tipped message) was deleted in the mean time!!! need to check for existence!
hasTip, ttt := tipTooltipExists(m.ReplyTo.ID, bot)
if hasTip {
// update the tooltip with new tippers
err := ttt.updateTooltip(bot, m.Sender, amount, !initializedWallet)
if err != nil {
log.Println(err)
// could not update the message (return false to )
return false
}
} else {
tipmsg := fmt.Sprintf(tooltipTipAmountMessage, amount)
userStr := GetUserStrMd(m.Sender)
tipmsg = fmt.Sprintf(tooltipSingleTipMessage, tipmsg, userStr)
if !initializedWallet {
tipmsg = tipmsg + fmt.Sprintf("\n%s", fmt.Sprintf(tooltipChatWithBotMessage, GetUserStrMd(bot.Telegram.Me)))
}
msg, err := bot.Telegram.Reply(m.ReplyTo, tipmsg, tb.Silent)
if err != nil {
log.Errorf("[tipTooltipHandler Reply] %s", err.Error())
// todo: in case of error we should do something better than just return 0
return false
}
message := NewTipTooltip(msg, TipAmount(amount), Tips(1))
message.Tippers = appendUinqueUsersToSlice(message.Tippers, m.Sender)
runtime.IgnoreError(bot.Bunt.Set(message))
}
// first call will return false, every following call will return true
return hasTip
}
// updateToolTip updates existing tip tool tip in Telegram
func (ttt *TipTooltip) updateTooltip(bot *TipBot, user *tb.User, amount int, notInitializedWallet bool) error {
ttt.TipAmount += amount
ttt.Ntips += 1
ttt.Tippers = appendUinqueUsersToSlice(ttt.Tippers, user)
ttt.LastTip = time.Now()
err := ttt.editTooltip(bot, notInitializedWallet)
if err != nil {
return err
}
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.Itoa(user.ID) {
log.Debugln("loading persistent tip tool tip messages")
ttt := &TipTooltip{}
err := json.Unmarshal([]byte(value), ttt)
if err != nil {
log.Errorln(err)
}
err = ttt.editTooltip(&bot, false)
if err != nil {
log.Errorf("[tipTooltipInitializedHandler] could not edit tooltip: %s", err.Error())
}
}
return true
})
return err
}))
}
func (ttt TipTooltip) Key() string {
return fmt.Sprintf("tip-tool-tip:%s", strconv.Itoa(ttt.Message.Message.ReplyTo.ID))
}
// editTooltip updates the tooltip message with the new tip amount and tippers and edits it
func (ttt *TipTooltip) editTooltip(bot *TipBot, notInitializedWallet bool) error {
tipToolTip := ttt.getUpdatedTipTooltipMessage(GetUserStrMd(bot.Telegram.Me), notInitializedWallet)
m, err := bot.Telegram.Edit(ttt.Message.Message, tipToolTip)
if err != nil {
return err
}
ttt.Message.Message.Text = m.Text
return nil
}
@@ -1,4 +1,4 @@
package main
package telegram
import (
"testing"
@@ -44,7 +44,7 @@ func Test_getTippersString(t *testing.T) {
func TestMessage_getTooltipMessage(t *testing.T) {
type fields struct {
Message *tb.Message
Message Message
TipAmount int
Ntips int
LastTip time.Time
@@ -65,27 +65,27 @@ func TestMessage_getTooltipMessage(t *testing.T) {
{
name: "1",
args: args{botUserName: "@test-bot", notInitializedWallet: true},
fields: fields{Message: &tb.Message{}, TipAmount: 10, Ntips: 1, Tippers: append(tippers, tipper1)},
fields: fields{Message: Message{}, TipAmount: 10, Ntips: 1, Tippers: append(tippers, tipper1)},
want: "🏅 10 sat (by @username1)\n🗑 Chat with @test-bot to manage your wallet.",
},
{
name: "2",
args: args{botUserName: "@test-bot", notInitializedWallet: true},
fields: fields{Message: &tb.Message{}, TipAmount: 100, Ntips: 6, Tippers: append(tippers, tipper1, tipper2, tipper3, tipper4, tipper5, tipper6)},
fields: fields{Message: Message{}, TipAmount: 100, Ntips: 6, Tippers: append(tippers, tipper1, tipper2, tipper3, tipper4, tipper5, tipper6)},
want: "🏅 100 sat (6 tips by @username1, @username2, @username3, @username4, @username5, ... and others)\n🗑 Chat with @test-bot to manage your wallet.",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
x := Message{
x := TipTooltip{
Message: tt.fields.Message,
TipAmount: tt.fields.TipAmount,
Ntips: tt.fields.Ntips,
LastTip: tt.fields.LastTip,
Tippers: tt.fields.Tippers,
}
if got := x.getTooltipMessage(tt.args.botUserName, tt.args.notInitializedWallet); got != tt.want {
t.Errorf("getTooltipMessage() = %v, want %v", got, tt.want)
if got := x.getUpdatedTipTooltipMessage(tt.args.botUserName, tt.args.notInitializedWallet); got != tt.want {
t.Errorf("getUpdatedTipTooltipMessage() = %v, want %v", got, tt.want)
}
})
}
+143
View File
@@ -0,0 +1,143 @@
package telegram
import (
"fmt"
"time"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
tb "gopkg.in/tucnak/telebot.v2"
)
const (
balanceTooLowMessage = "Your balance is too low."
)
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 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 *lnbits.User, to *lnbits.User, amount int, 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) {
// 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 *lnbits.User, to *lnbits.User, amount int, memo string) (bool, error) {
fromUserStr := GetUserStr(from.Telegram)
toUserStr := GetUserStr(to.Telegram)
t.FromWallet = from.Wallet.ID
t.FromLNbitsID = from.ID
// check if fromUser has balance
balance, err := bot.GetUserBalance(from)
if err != nil {
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(balanceTooLowMessage)
log.Errorf("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("[SendTransaction] Error: Could not create invoice for user %s", toUserStr)
log.Errorln(errmsg)
return false, err
}
// pay invoice
_, err = from.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, bot.Client)
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
}
+24
View File
@@ -0,0 +1,24 @@
package telegram
import (
"context"
"github.com/nicksnyder/go-i18n/v2/i18n"
log "github.com/sirupsen/logrus"
)
func Translate(ctx context.Context, MessgeID string) string {
str, err := LoadPublicLocalizer(ctx).Localize(&i18n.LocalizeConfig{MessageID: MessgeID})
if err != nil {
log.Warnf("Error translating message %s: %s", MessgeID, err)
}
return str
}
func TranslateUser(ctx context.Context, MessgeID string) string {
str, err := LoadUserLocalizer(ctx).Localize(&i18n.LocalizeConfig{MessageID: MessgeID})
if err != nil {
log.Warnf("Error translating message %s: %s", MessgeID, err)
}
return str
}
+39 -48
View File
@@ -1,8 +1,9 @@
package main
package telegram
import (
"errors"
"fmt"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
@@ -12,25 +13,15 @@ import (
"gorm.io/gorm"
)
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 SetUserState(user *lnbits.User, bot TipBot, stateKey lnbits.UserStateKey, stateData string) {
user.StateKey = stateKey
user.StateData = stateData
bot.Database.Table("users").Where("name = ?", user.Name).Update("state_key", user.StateKey).Update("state_data", user.StateData)
}
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 ResetUserState(user *lnbits.User, bot TipBot) {
user.ResetState()
bot.Database.Table("users").Where("name = ?", user.Name).Update("state_key", 0).Update("state_data", "")
}
func GetUserStr(user *tb.User) string {
@@ -49,10 +40,14 @@ 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 {
@@ -64,59 +59,55 @@ func appendUinqueUsersToSlice(slice []*tb.User, i *tb.User) []*tb.User {
return append(slice, i)
}
func (bot *TipBot) UserInitializedWallet(user *tb.User) bool {
toUser, err := GetUser(user, *bot)
if err != nil {
return false
}
return !toUser.Initialized
}
func (bot *TipBot) GetUserBalance(user *lnbits.User) (amount int, err error) {
func (bot *TipBot) GetUserBalance(user *tb.User) (amount int, err error) {
// get user
fromUser, err := GetUser(user, *bot)
wallet, err := bot.Client.Info(*user.Wallet)
if err != nil {
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)
errmsg := fmt.Sprintf("[GetUserBalance] Error: Couldn't fetch user %s's info from LNbits: %s", GetUserStr(user.Telegram), err)
log.Errorln(errmsg)
return
}
fromUser.Wallet.Balance = wallet.Balance
err = UpdateUserRecord(fromUser, *bot)
user.Wallet.Balance = wallet.Balance
err = UpdateUserRecord(user, *bot)
if err != nil {
return
}
// msat to sat
amount = int(wallet.Balance) / 1000
log.Infof("[GetUserBalance] %s's balance: %d sat\n", GetUserStr(user), amount)
log.Infof("[GetUserBalance] %s's balance: %d sat\n", GetUserStr(user.Telegram), amount)
return
}
func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) error {
user := &lnbits.User{Telegram: tbUser}
// copyLowercaseUser will create a coy user and cast username to lowercase.
func (bot *TipBot) copyLowercaseUser(u *tb.User) *tb.User {
userCopy := *u
userCopy.Username = strings.ToLower(u.Username)
return &userCopy
}
func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) (*lnbits.User, error) {
userCopy := bot.copyLowercaseUser(tbUser)
user := &lnbits.User{Telegram: userCopy}
userStr := GetUserStr(tbUser)
log.Printf("[CreateWalletForTelegramUser] Creating wallet for user %s ... ", userStr)
err := bot.createWallet(user)
if err != nil {
errmsg := fmt.Sprintf("[CreateWalletForTelegramUser] Error: Could not create wallet for user %s", userStr)
log.Errorln(errmsg)
return err
return user, err
}
tx := bot.database.Save(user)
tx := bot.Database.Save(user)
if tx.Error != nil {
return tx.Error
return nil, tx.Error
}
log.Printf("[CreateWalletForTelegramUser] Wallet created for user %s. ", userStr)
return nil
return user, nil
}
func (bot *TipBot) UserHasWallet(user *tb.User) bool {
_, err := GetUser(user, *bot)
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
return false
func (bot *TipBot) UserExists(user *tb.User) (*lnbits.User, bool) {
lnbitUser, err := GetUser(user, *bot)
if err != nil || errors.Is(err, gorm.ErrRecordNotFound) {
return nil, false
}
return true
return lnbitUser, true
}
-52
View File
@@ -1,52 +0,0 @@
package main
import (
"bytes"
"fmt"
"strings"
log "github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode"
tb "gopkg.in/tucnak/telebot.v2"
)
var (
walletConnectMessage = "🔗 *Link your wallet*\n\n" +
"⚠️ Never share the URL or the QR code with anyone or they will be able to access your funds.\n\n" +
"- *BlueWallet:* Press *New wallet*, *Import wallet*, *Scan or import a file*, and scan the QR code.\n" +
"- *Zeus:* Copy the URL below, press *Add a new node*, *Import* (the URL), *Save Node Config*."
)
func (bot TipBot) lndhubHandler(m *tb.Message) {
// check and print all commands
bot.anyTextHandler(m)
// reply only in private message
if m.Chat.Type != tb.ChatPrivate {
// delete message
NewMessage(m).Dispose(0, bot.telegram)
}
// first check whether the user is initialized
fromUser, err := GetUser(m.Sender, bot)
if err != nil {
log.Errorf("[/balance] Error: %s", err)
return
}
bot.telegram.Send(m.Sender, walletConnectMessage)
lnbitsUrl := Configuration.LnbitsPublicUrl
if !strings.HasSuffix(lnbitsUrl, "/") {
lnbitsUrl = lnbitsUrl + "/"
}
lndhubUrl := fmt.Sprintf("lndhub://admin:%s@%slndhub/ext/", fromUser.Wallet.Adminkey, lnbitsUrl)
// create qr code
qr, err := qrcode.Encode(lndhubUrl, qrcode.Medium, 256)
if err != nil {
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err)
log.Errorln(errmsg)
return
}
// send the invoice data to user
bot.telegram.Send(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
}
+11 -1
View File
@@ -1,6 +1,12 @@
package main
import (
"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"
)
@@ -17,12 +23,16 @@ func main() {
// set logger
setLogger()
defer withRecovery()
bot := NewBot()
bot := telegram.NewBot()
webhook.NewServer(&bot)
lnurl.NewServer(&bot)
price.NewPriceWatcher().Start()
bot.Start()
}
func withRecovery() {
if r := recover(); r != nil {
log.Errorln("Recovered panic: ", r)
debug.PrintStack()
}
}
-67
View File
@@ -1,67 +0,0 @@
package main
import (
"time"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
)
type Message struct {
Message *tb.Message
TipAmount int
Ntips int
LastTip time.Time
Tippers []*tb.User
}
const maxNamesInTipperMessage = 5
type messageOption func(m *Message)
func TipAmount(amount int) messageOption {
return func(m *Message) {
m.TipAmount = amount
}
}
func Tips(nTips int) messageOption {
return func(m *Message) {
m.LastTip = time.Now()
m.Ntips = nTips
}
}
func NewMessage(m *tb.Message, opts ...messageOption) *Message {
msg := &Message{
Message: m,
Tippers: make([]*tb.User, 0),
}
for _, opt := range opts {
opt(msg)
}
return msg
}
func (x Message) Dispose(duration time.Duration, telegram *tb.Bot) {
// do not delete messages from private chat
if x.Message.Private() {
return
}
go func() {
time.Sleep(duration)
err := telegram.Delete(x.Message)
if err != nil {
log.Println(err.Error())
return
}
}()
}
func removeMessage(messages []*Message, s int) []*Message {
if len(messages) == 1 {
return make([]*Message, 0)
}
return append(messages[:s], messages[s+1:]...)
}
-174
View File
@@ -1,174 +0,0 @@
package main
import (
"fmt"
"strings"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
decodepay "github.com/fiatjaf/ln-decodepay"
tb "gopkg.in/tucnak/telebot.v2"
)
const (
paymentCancelledMessage = "🚫 Payment cancelled."
invoicePaidMessage = "⚡️ Invoice paid."
invoicePrivateChatOnlyErrorMessage = "You can pay invoices only in the private chat with the bot."
invalidInvoiceHelpMessage = "Did you enter a valid Lightning invoice?"
invoiceNoAmountMessage = "🚫 Can't pay invoices without an amount."
insufficientFundsMessage = "🚫 Insufficient funds. You have %d sat but you need at least %d sat."
feeReserveMessage = "⚠️ Sending your entire balance might fail because of network fees. If it fails, try sending a bit less."
invoicePaymentFailedMessage = "🚫 Failed to pay invoice: %s"
confirmPayInvoiceMessage = "Do you want to pay this invoice?\n\n💸 Amount: %d sat"
confirmPayAppendMemo = "\n✉️ %s"
payHelpText = "📖 Oops, that didn't work. %s\n\n" +
"*Usage:* `/pay <invoice>`\n" +
"*Example:* `/pay lnbc20n1psscehd...`"
)
func helpPayInvoiceUsage(errormsg string) string {
if len(errormsg) > 0 {
return fmt.Sprintf(payHelpText, fmt.Sprintf("%s", errormsg))
} else {
return fmt.Sprintf(payHelpText, "")
}
}
// confirmPaymentHandler invoked on "/pay lnbc..." command
func (bot TipBot) confirmPaymentHandler(m *tb.Message) {
// check and print all commands
bot.anyTextHandler(m)
if m.Chat.Type != tb.ChatPrivate {
// delete message
NewMessage(m).Dispose(0, bot.telegram)
bot.telegram.Send(m.Sender, helpPayInvoiceUsage(invoicePrivateChatOnlyErrorMessage))
return
}
if len(strings.Split(m.Text, " ")) < 2 {
NewMessage(m).Dispose(0, bot.telegram)
bot.telegram.Send(m.Sender, helpPayInvoiceUsage(""))
return
}
user, err := GetUser(m.Sender, bot)
if err != nil {
NewMessage(m).Dispose(0, bot.telegram)
errmsg := fmt.Sprintf("[/pay] Error: Could not GetUser: %s", err)
log.Errorln(errmsg)
return
}
userStr := GetUserStr(m.Sender)
paymentRequest, err := getArgumentFromCommand(m.Text, 1)
if err != nil {
NewMessage(m).Dispose(0, bot.telegram)
bot.telegram.Send(m.Sender, helpPayInvoiceUsage(invalidInvoiceHelpMessage))
errmsg := fmt.Sprintf("[/pay] Error: Could not getArgumentFromCommand: %s", err)
log.Errorln(errmsg)
return
}
paymentRequest = strings.ToLower(paymentRequest)
// get rid of the URI prefix
paymentRequest = strings.TrimPrefix(paymentRequest, "lightning:")
// decode invoice
bolt11, err := decodepay.Decodepay(paymentRequest)
if err != nil {
bot.telegram.Send(m.Sender, helpPayInvoiceUsage(invalidInvoiceHelpMessage))
errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err)
log.Errorln(errmsg)
return
}
amount := int(bolt11.MSatoshi / 1000)
if amount <= 0 {
bot.telegram.Send(m.Sender, invoiceNoAmountMessage)
errmsg := fmt.Sprint("[/pay] Error: invoice without amount")
log.Errorln(errmsg)
return
}
// check user balance first
balance, err := bot.GetUserBalance(m.Sender)
if err != nil {
NewMessage(m).Dispose(0, bot.telegram)
errmsg := fmt.Sprintf("[/pay] Error: Could not get user balance: %s", err)
log.Errorln(errmsg)
return
}
if amount > balance {
NewMessage(m).Dispose(0, bot.telegram)
bot.telegram.Send(m.Sender, fmt.Sprintf(insufficientFundsMessage, balance, amount))
return
}
// send warning that the invoice might fail due to missing fee reserve
if float64(amount) > float64(balance)*0.99 {
bot.telegram.Send(m.Sender, feeReserveMessage)
}
log.Printf("[/pay] User: %s, amount: %d sat.", userStr, amount)
user.StateKey = lnbits.UserStateConfirmPayment
user.StateData = paymentRequest
err = UpdateUserRecord(user, bot)
if err != nil {
log.Printf("[UpdateUserRecord] User: %s Error: %s", userStr, err.Error())
return
}
// // // create inline buttons
paymentConfirmationMenu.Inline(paymentConfirmationMenu.Row(btnPay, btnCancelPay))
confirmText := fmt.Sprintf(confirmPayInvoiceMessage, amount)
if len(bolt11.Description) > 0 {
confirmText = confirmText + fmt.Sprintf(confirmPayAppendMemo, MarkdownEscape(bolt11.Description))
}
bot.telegram.Send(m.Sender, confirmText, paymentConfirmationMenu)
}
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
func (bot TipBot) cancelPaymentHandler(c *tb.Callback) {
// reset state immediately
user, err := GetUser(c.Sender, bot)
if err != nil {
return
}
user.ResetState()
err = UpdateUserRecord(user, bot)
bot.telegram.Delete(c.Message)
_, err = bot.telegram.Send(c.Sender, paymentCancelledMessage)
if err != nil {
log.WithField("message", paymentCancelledMessage).WithField("user", c.Sender.ID).Printf("[Send] %s", err.Error())
return
}
}
// payHandler when user clicked pay "X" on payment confirmation
func (bot TipBot) payHandler(c *tb.Callback) {
bot.telegram.Edit(c.Message, c.Message.Text, &tb.ReplyMarkup{})
user, err := GetUser(c.Sender, bot)
if err != nil {
log.Printf("[GetUser] User: %d: %s", c.Sender.ID, err.Error())
return
}
if user.StateKey == lnbits.UserStateConfirmPayment {
invoiceString := user.StateData
// reset state immediatelly
user.ResetState()
err = UpdateUserRecord(user, bot)
userStr := GetUserStr(c.Sender)
// pay invoice
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoiceString}, *user.Wallet)
if err != nil {
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of user %s: %s", userStr, err)
bot.telegram.Send(c.Sender, fmt.Sprintf(invoicePaymentFailedMessage, err))
log.Errorln(errmsg)
return
}
bot.telegram.Send(c.Sender, invoicePaidMessage)
log.Printf("[/pay] User %s paid invoice %s", userStr, invoice.PaymentHash)
return
}
}
-73
View File
@@ -1,73 +0,0 @@
package main
import (
"fmt"
"image"
"image/jpeg"
"strings"
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
"github.com/makiuchi-d/gozxing"
"github.com/makiuchi-d/gozxing/qrcode"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
)
var (
photoQrNotRecognizedMessage = "🚫 Could not regocognize a Lightning invoice. Try to center the QR code, crop the photo, or zoom in."
photoInvoiceRecognizedMessage = "✅ Invoice:\n`%s`"
)
// TryRecognizeInvoiceFromQrCode will try to read an invoice string from a qr code and invoke the payment handler.
func TryRecognizeInvoiceFromQrCode(img image.Image) (*gozxing.Result, error) {
// check for qr code
bmp, _ := gozxing.NewBinaryBitmapFromImage(img)
// decode image
qrReader := qrcode.NewQRCodeReader()
result, err := qrReader.Decode(bmp, nil)
if err != nil {
return nil, err
}
payload := strings.ToLower(result.String())
if lightning.IsInvoice(payload) {
// create payment command payload
// invoke payment confirmation handler
return result, nil
}
return nil, fmt.Errorf("no codes found")
}
// privatePhotoHandler is the handler function for every photo from a private chat that the bot receives
func (bot TipBot) privatePhotoHandler(m *tb.Message) {
if m.Chat.Type != tb.ChatPrivate {
return
}
if m.Photo == nil {
return
}
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, "<Photo>")
// get file reader closer from telegram api
reader, err := bot.telegram.GetFile(m.Photo.MediaFile())
if err != nil {
log.Errorf("Getfile error: %v\n", err)
return
}
// decode to jpeg image
img, err := jpeg.Decode(reader)
if err != nil {
log.Errorf("image.Decode error: %v\n", err)
return
}
data, err := TryRecognizeInvoiceFromQrCode(img)
if err != nil {
log.Errorf("tryRecognizeQrCodes error: %v\n", err)
bot.telegram.Send(m.Sender, photoQrNotRecognizedMessage)
return
}
bot.telegram.Send(m.Sender, fmt.Sprintf(photoInvoiceRecognizedMessage, data.String()))
// invoke payment handler
m.Text = fmt.Sprintf("/pay %s", data.String())
bot.confirmPaymentHandler(m)
}
+21 -3
View File
@@ -1,18 +1,36 @@
package lightning
import (
"net/mail"
"strings"
)
// IsInvoice is used to check if a string matches lnbc invoide pattern.
// todo -- probably should add regex and validate length
func IsInvoice(invoice string) bool {
func IsInvoice(message string) bool {
message = strings.ToLower(message)
// invoice string must start with lnbc or lightning:lnbc
if strings.HasPrefix(invoice, "lnbc") || strings.HasPrefix(invoice, "lightning:lnbc") {
if strings.HasPrefix(message, "lnbc") || strings.HasPrefix(message, "lightning:lnbc") {
// invoice string must be a single word
if !strings.Contains(invoice, " ") {
if !strings.Contains(message, " ") {
return true
}
}
return false
}
func IsLnurl(message string) bool {
message = strings.ToLower(message)
if strings.HasPrefix(message, "lnurl") {
// string must be a single word
if !strings.Contains(message, " ") {
return true
}
}
return false
}
func IsLightningAddress(address string) bool {
_, err := mail.ParseAddress(address)
return err == nil
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 172 KiB

After

Width:  |  Height:  |  Size: 107 KiB

-278
View File
@@ -1,278 +0,0 @@
package main
import (
"fmt"
"strconv"
"strings"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
tb "gopkg.in/tucnak/telebot.v2"
)
const (
sendValidAmountMessage = "Did you enter a valid amount?"
sendUserNotFoundMessage = "User %s could not be found. You can /send only to Telegram tags like @%s."
sendIsNotAUsser = "🚫 %s is not a username. You can /send only to Telegram tags like @%s."
sendUserHasNoWalletMessage = "🚫 User %s hasn't created a wallet yet."
sendSentMessage = "💸 %d sat sent to %s."
sendReceivedMessage = "🏅 %s has sent you %d sat."
sendErrorMessage = "🚫 Transaction failed: %s"
confirmSendInvoiceMessage = "Do you want to pay to %s?\n\n💸 Amount: %d sat"
confirmSendAppendMemo = "\n✉️ %s"
sendCancelledMessage = "🚫 Send cancelled."
errorTryLaterMessage = "🚫 Internal error. Please try again later.."
sendHelpText = "📖 Oops, that didn't work. %s\n\n" +
"*Usage:* `/send <amount> <user> [<memo>]`\n" +
"*Example:* `/send 1000 @LightningTipBot I just like the bot ❤️`"
)
func helpSendUsage(errormsg string) string {
if len(errormsg) > 0 {
return fmt.Sprintf(sendHelpText, fmt.Sprintf("%s", errormsg))
} else {
return fmt.Sprintf(sendHelpText, "")
}
}
func SendCheckSyntax(m *tb.Message) (bool, string) {
arguments := strings.Split(m.Text, " ")
if len(arguments) < 2 {
return false, "Did you enter an amount and a recipient?"
}
if len(arguments) < 3 {
return false, "Did you enter a recipient?"
}
if !strings.HasPrefix(arguments[0], "/send") {
return false, "Did you enter a valid command?"
}
return true, ""
}
// confirmPaymentHandler invoked on "/send 123 @user" command
func (bot *TipBot) confirmSendHandler(m *tb.Message) {
// check and print all commands
bot.anyTextHandler(m)
// If the send is a reply, then trigger /tip handler
if m.IsReply() {
bot.tipHandler(m)
return
}
if ok, err := SendCheckSyntax(m); !ok {
bot.telegram.Send(m.Sender, helpSendUsage(err))
NewMessage(m).Dispose(0, bot.telegram)
return
}
// get send amount
amount, err := decodeAmountFromCommand(m.Text)
if err != nil || amount < 1 {
errmsg := fmt.Sprintf("[/send] Error: Send amount not valid.")
log.Errorln(errmsg)
// immediately delete if the amount is bullshit
NewMessage(m).Dispose(0, bot.telegram)
bot.telegram.Send(m.Sender, helpSendUsage(sendValidAmountMessage))
return
}
// SEND COMMAND IS VALID
// check for memo in command
sendMemo := ""
if len(strings.Split(m.Text, " ")) > 3 {
sendMemo = strings.SplitN(m.Text, " ", 4)[3]
if len(sendMemo) > 200 {
sendMemo = sendMemo[:200]
sendMemo = sendMemo + "..."
}
}
if len(m.Entities) < 2 {
arg, err := getArgumentFromCommand(m.Text, 2)
if err != nil {
log.Errorln(err.Error())
return
}
arg = MarkdownEscape(arg)
NewMessage(m).Dispose(0, bot.telegram)
errmsg := fmt.Sprintf("Error: User %s could not be found", arg)
bot.telegram.Send(m.Sender, helpSendUsage(fmt.Sprintf(sendUserNotFoundMessage, arg, arg)))
log.Errorln(errmsg)
return
}
if m.Entities[1].Type != "mention" {
arg, err := getArgumentFromCommand(m.Text, 2)
if err != nil {
NewMessage(m).Dispose(0, bot.telegram)
log.Errorln(err.Error())
return
}
arg = MarkdownEscape(arg)
NewMessage(m).Dispose(0, bot.telegram)
errmsg := fmt.Sprintf("Error: %s is not a user", arg)
bot.telegram.Send(m.Sender, fmt.Sprintf(sendIsNotAUsser, arg, arg))
log.Errorln(errmsg)
return
}
toUserStrMention := m.Text[m.Entities[1].Offset : m.Entities[1].Offset+m.Entities[1].Length]
toUserStrWithoutAt := strings.TrimPrefix(toUserStrMention, "@")
err = bot.parseCmdDonHandler(m)
if err == nil {
return
}
toUserDb := &lnbits.User{}
tx := bot.database.Where("telegram_username = ?", toUserStrWithoutAt).First(toUserDb)
if tx.Error != nil || toUserDb.Wallet == nil || toUserDb.Initialized == false {
NewMessage(m).Dispose(0, bot.telegram)
errmsg := fmt.Sprintf(sendUserHasNoWalletMessage, MarkdownEscape(toUserStrMention))
log.Println("[/send] Error: " + errmsg)
bot.telegram.Send(m.Sender, errmsg)
return
}
// string that holds all information about the send payment
sendData := strconv.Itoa(toUserDb.Telegram.ID) + "|" + toUserStrWithoutAt + "|" +
strconv.Itoa(amount)
if len(sendMemo) > 0 {
sendData = sendData + "|" + sendMemo
}
// save the send data to the database
log.Debug(sendData)
user, err := GetUser(m.Sender, *bot)
if err != nil {
NewMessage(m).Dispose(0, bot.telegram)
log.Printf("[/send] Error: %s\n", err.Error())
bot.telegram.Send(m.Sender, fmt.Sprint(errorTryLaterMessage))
return
}
user.StateKey = lnbits.UserStateConfirmSend
user.StateData = sendData
err = UpdateUserRecord(user, *bot)
if err != nil {
log.Printf("[UpdateUserRecord] User: %s Error: %s", GetUserStr(m.Sender), err.Error())
return
}
sendConfirmationMenu.Inline(sendConfirmationMenu.Row(btnSend, btnCancelSend))
confirmText := fmt.Sprintf(confirmSendInvoiceMessage, MarkdownEscape(toUserStrMention), amount)
if len(sendMemo) > 0 {
confirmText = confirmText + fmt.Sprintf(confirmSendAppendMemo, MarkdownEscape(sendMemo))
}
_, err = bot.telegram.Send(m.Sender, confirmText, sendConfirmationMenu)
if err != nil {
log.Error("[confirmSendHandler]" + err.Error())
return
}
}
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
func (bot *TipBot) cancelSendHandler(c *tb.Callback) {
// reset state immediately
user, err := GetUser(c.Sender, *bot)
if err != nil {
log.Errorln(err.Error())
return
}
user.ResetState()
err = UpdateUserRecord(user, *bot)
if err != nil {
log.Errorln(err.Error())
return
}
// delete the confirmation message
err = bot.telegram.Delete(c.Message)
if err != nil {
log.Errorln("[cancelSendHandler] " + err.Error())
}
// notify the user
_, err = bot.telegram.Send(c.Sender, sendCancelledMessage)
if err != nil {
log.WithField("message", sendCancelledMessage).WithField("user", c.Sender.ID).Printf("[Send] %s", err.Error())
return
}
}
// sendHandler invoked when user clicked send on payment confirmation
func (bot *TipBot) sendHandler(c *tb.Callback) {
// remove buttons from confirmation message
_, err := bot.telegram.Edit(c.Message, MarkdownEscape(c.Message.Text), &tb.ReplyMarkup{})
if err != nil {
log.Errorln("[sendHandler] " + err.Error())
}
// decode callback data
// log.Debug("[sendHandler] Callback: %s", c.Data)
user, err := GetUser(c.Sender, *bot)
if err != nil {
log.Printf("[GetUser] User: %d: %s", c.Sender.ID, err.Error())
return
}
if user.StateKey != lnbits.UserStateConfirmSend {
log.Errorf("[sendHandler] User StateKey does not match! User: %d: StateKey: %d", c.Sender.ID, user.StateKey)
return
}
// decode StateData in which we have information about the send payment
splits := strings.Split(user.StateData, "|")
if len(splits) < 3 {
log.Error("[sendHandler] Not enough arguments in callback data")
log.Errorf("user.StateData: %s", user.StateData)
return
}
toId, err := strconv.Atoi(splits[0])
if err != nil {
log.Errorln("[sendHandler] " + err.Error())
}
toUserStrWithoutAt := splits[1]
amount, err := strconv.Atoi(splits[2])
if err != nil {
log.Errorln("[sendHandler] " + err.Error())
}
sendMemo := ""
if len(splits) > 3 {
sendMemo = strings.Join(splits[3:], "|")
}
// reset state
user.ResetState()
err = UpdateUserRecord(user, *bot)
if err != nil {
log.Errorln(err.Error())
return
}
// we can now get the wallets of both users
to := &tb.User{ID: toId, Username: toUserStrWithoutAt}
from := c.Sender
toUserStrMd := GetUserStrMd(to)
fromUserStrMd := GetUserStrMd(from)
toUserStr := GetUserStr(to)
fromUserStr := GetUserStr(from)
transactionMemo := fmt.Sprintf("Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
t := NewTransaction(bot, from, to, amount, TransactionType("send"))
t.Memo = transactionMemo
success, err := t.Send()
if !success || err != nil {
// NewMessage(m).Dispose(0, bot.telegram)
bot.telegram.Send(c.Sender, fmt.Sprintf(sendErrorMessage, err))
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err)
log.Errorln(errmsg)
return
}
bot.telegram.Send(from, fmt.Sprintf(sendSentMessage, amount, toUserStrMd))
bot.telegram.Send(to, fmt.Sprintf(sendReceivedMessage, fromUserStrMd, amount))
// send memo if it was present
if len(sendMemo) > 0 {
bot.telegram.Send(to, fmt.Sprintf("✉️ %s", MarkdownEscape(sendMemo)))
}
return
}
-35
View File
@@ -1,35 +0,0 @@
package main
import (
"strings"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
tb "gopkg.in/tucnak/telebot.v2"
)
const (
initWalletMessage = "You don't have a wallet yet. Enter */start*"
)
func (bot TipBot) anyTextHandler(m *tb.Message) {
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
if m.Chat.Type != tb.ChatPrivate {
return
}
// check if user is in database, if not, initialize wallet
if !bot.UserHasWallet(m.Sender) {
bot.startHandler(m)
return
}
// could be an invoice
invoiceString := strings.ToLower(m.Text)
if lightning.IsInvoice(invoiceString) {
m.Text = "/pay " + invoiceString
bot.confirmPaymentHandler(m)
return
}
}
-153
View File
@@ -1,153 +0,0 @@
package main
import (
"fmt"
"strings"
"time"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
)
const (
tipDidYouReplyMessage = "Did you reply to a message to tip? To reply to any message, right-click -> Reply on your computer or swipe the message on your phone. If you want to send directly to another Telegram user's wallet, use the /send command."
tipEnterAmountMessage = "Did you enter an amount?"
tipValidAmountMessage = "Did you enter a valid amount?"
tipYourselfMessage = "📖 You can't tip yourself."
tipSentMessage = "💸 %d sat sent to %s."
tipReceivedMessage = "🏅 %s has tipped you %d sat."
tipErrorMessage = "🚫 Transaction failed: %s"
tipHelpText = "📖 Oops, that didn't work. %s\n\n" +
"*Usage:* `/tip <amount> [<memo>]`\n" +
"*Example:* `/tip 1000 Dank meme!`"
)
func helpTipUsage(errormsg string) string {
if len(errormsg) > 0 {
return fmt.Sprintf(tipHelpText, fmt.Sprintf("%s", errormsg))
} else {
return fmt.Sprintf(tipHelpText, "")
}
}
func TipCheckSyntax(m *tb.Message) (bool, string) {
arguments := strings.Split(m.Text, " ")
if len(arguments) < 2 {
return false, tipEnterAmountMessage
}
return true, ""
}
func (bot *TipBot) tipHandler(m *tb.Message) {
// check and print all commands
bot.anyTextHandler(m)
// only if message is a reply
if !m.IsReply() {
NewMessage(m).Dispose(0, bot.telegram)
bot.telegram.Send(m.Sender, helpTipUsage(fmt.Sprintf(tipDidYouReplyMessage)))
return
}
if ok, err := TipCheckSyntax(m); !ok {
bot.telegram.Send(m.Sender, helpTipUsage(err))
NewMessage(m).Dispose(0, bot.telegram)
return
}
// get tip amount
amount, err := decodeAmountFromCommand(m.Text)
if err != nil || amount < 1 {
errmsg := fmt.Sprintf("[/tip] Error: Tip amount not valid.")
// immediately delete if the amount is bullshit
NewMessage(m).Dispose(0, bot.telegram)
bot.telegram.Send(m.Sender, helpTipUsage(tipValidAmountMessage))
log.Errorln(errmsg)
return
}
err = bot.parseCmdDonHandler(m)
if err == nil {
return
}
// TIP COMMAND IS VALID
to := m.ReplyTo.Sender
from := m.Sender
if from.ID == to.ID {
NewMessage(m).Dispose(0, bot.telegram)
bot.telegram.Send(m.Sender, tipYourselfMessage)
return
}
toUserStrMd := GetUserStrMd(m.ReplyTo.Sender)
fromUserStrMd := GetUserStrMd(from)
toUserStr := GetUserStr(m.ReplyTo.Sender)
fromUserStr := GetUserStr(from)
if !bot.UserHasWallet(to) {
log.Infof("[/tip] User %s has no wallet.", toUserStr)
err = bot.CreateWalletForTelegramUser(to)
if err != nil {
errmsg := fmt.Errorf("[/tip] Error: Could not create wallet for %s", toUserStr)
log.Errorln(errmsg)
return
}
}
// check for memo in command
tipMemo := ""
if len(strings.Split(m.Text, " ")) > 2 {
tipMemo = strings.SplitN(m.Text, " ", 3)[2]
if len(tipMemo) > 200 {
tipMemo = tipMemo[:200]
tipMemo = tipMemo + "..."
}
}
// todo: user new get username function to get userStrings
transactionMemo := fmt.Sprintf("Tip from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
t := NewTransaction(bot, from, to, amount, TransactionType("tip"), TransactionChat(m.Chat))
t.Memo = transactionMemo
success, err := t.Send()
if !success {
NewMessage(m).Dispose(0, bot.telegram)
if err != nil {
bot.telegram.Send(m.Sender, fmt.Sprintf(tipErrorMessage, err))
} else {
bot.telegram.Send(m.Sender, fmt.Sprintf(tipErrorMessage, "please try again later"))
}
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err)
log.Errorln(errMsg)
return
}
// delete the tip message after a few seconds, this is default behaviour
NewMessage(m).Dispose(time.Second*time.Duration(Configuration.MessageDisposeDuration), bot.telegram)
// update tooltip if necessary
messageHasTip := tipTooltipHandler(m, from, bot, amount, bot.UserInitializedWallet(to))
log.Infof("[tip] %d sat from %s to %s", amount, fromUserStr, toUserStr)
// notify users
_, err = bot.telegram.Send(from, fmt.Sprintf(tipSentMessage, amount, toUserStrMd))
if err != nil {
errmsg := fmt.Errorf("[/tip] Error: Send message to %s: %s", toUserStr, err)
log.Errorln(errmsg)
return
}
// forward tipped message to user once
if !messageHasTip {
bot.telegram.Forward(to, m.ReplyTo, tb.Silent)
}
bot.telegram.Send(to, fmt.Sprintf(tipReceivedMessage, fromUserStrMd, amount))
if len(tipMemo) > 0 {
bot.telegram.Send(to, fmt.Sprintf("✉️ %s", MarkdownEscape(tipMemo)))
}
return
}
-149
View File
@@ -1,149 +0,0 @@
package main
import (
"fmt"
"strings"
"time"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
)
func (bot *TipBot) cleanupTipsFromMemory() {
go func() {
defer withRecovery()
for {
for userId, userTips := range bot.tips {
for i, tip := range userTips {
if time.Now().Sub(tip.LastTip) > (time.Hour*24)*7 {
userTips = removeMessage(userTips, i)
err := bot.telegram.Delete(tip.Message)
if err != nil {
log.WithField("error", err.Error()).Error("could not delete tip tool tip")
}
bot.tips[userId] = userTips
}
}
}
time.Sleep(time.Hour)
}
}()
}
// updateToolTip updates existing tip tool tip in telegram
func (x *Message) updateTooltip(bot *TipBot, user *tb.User, amount int, notInitializedWallet bool) {
x.TipAmount += amount
x.Ntips += 1
x.Tippers = appendUinqueUsersToSlice(x.Tippers, user)
x.LastTip = time.Now()
userTips := bot.tips[x.Message.ReplyTo.Sender.ID]
for _, tip := range userTips {
if tip.Message.ReplyTo.Sender.ID == x.Message.ReplyTo.Sender.ID {
err := x.editTooltip(bot, notInitializedWallet)
if err != nil {
log.Printf("[updateTooltip] could not edit tooltip: %s", err.Error())
continue
}
tip = x
}
}
bot.tips[x.Message.ReplyTo.Sender.ID] = userTips
}
func (x *Message) editTooltip(bot *TipBot, notInitializedWallet bool) error {
tipToolTip := x.getTooltipMessage(GetUserStrMd(bot.telegram.Me), notInitializedWallet)
m, err := bot.telegram.Edit(x.Message, tipToolTip)
if err != nil {
return err
}
x.Message.Text = m.Text
return nil
}
func tipTooltipInitializedHandler(user *tb.User, bot TipBot) {
for _, tip := range bot.tips[user.ID] {
if tip.Message.ReplyTo.Sender.ID == user.ID {
err := tip.editTooltip(&bot, false)
if err != nil {
log.Printf("[tipTooltipInitializedHandler] could not edit tooltip: %s", err.Error())
continue
}
}
}
}
// getTippersString joins all tippers username or telegram id's as mentions (@username or [inline mention of a user](tg://user?id=123456789))
func getTippersString(tippers []*tb.User) string {
var tippersStr string
for _, uniqueUser := range tippers {
userStr := GetUserStrMd(uniqueUser)
tippersStr += fmt.Sprintf("%s, ", userStr)
}
// get rid of the trailing comma
if len(tippersStr) > 2 {
tippersStr = tippersStr[:len(tippersStr)-2]
}
tippersSlice := strings.Split(tippersStr, " ")
// crop the message to the max length
if len(tippersSlice) > maxNamesInTipperMessage {
// tippersStr = tippersStr[:50]
tippersStr = strings.Join(tippersSlice[:maxNamesInTipperMessage], " ")
tippersStr = tippersStr + " ... and others"
}
return tippersStr
}
// getTooltipMessage will return the full tip tool tip
func (x Message) getTooltipMessage(botUserName string, notInitializedWallet bool) string {
tippersStr := getTippersString(x.Tippers)
tipToolTipMessage := fmt.Sprintf("🏅 %d sat", x.TipAmount)
if len(x.Tippers) > 1 {
tipToolTipMessage = fmt.Sprintf("%s (%d tips by %s)", tipToolTipMessage, x.Ntips, tippersStr)
} else {
tipToolTipMessage = fmt.Sprintf("%s (by %s)", tipToolTipMessage, tippersStr)
}
if notInitializedWallet {
tipToolTipMessage = tipToolTipMessage + fmt.Sprintf("\n🗑 Chat with %s to manage your wallet.", botUserName)
}
return tipToolTipMessage
}
// tipTooltipExists checks if this tip is already known
func tipTooltipExists(m *tb.Message, bot *TipBot) (bool, *Message) {
for _, tip := range bot.tips[m.ReplyTo.Sender.ID] {
if tip.Message.ReplyTo != nil && m.ReplyTo != nil {
if tip.Message.ReplyTo.ID == m.ReplyTo.ID {
return true, tip
}
}
}
return false, nil
}
// tipTooltipHandler function to update the tooltip below a tipped message. either updates or creates initial tip tool tip
func tipTooltipHandler(m *tb.Message, user *tb.User, bot *TipBot, amount int, notInitializedWallet bool) bool {
// todo: this crashes if the tooltip message (maybe also the original tipped message) was deleted in the mean time!!! need to check for existence!
ok, tipMessage := tipTooltipExists(m, bot)
if ok {
// update the tooltip with new tippers
tipMessage.updateTooltip(bot, user, amount, notInitializedWallet)
} else {
tipmsg := fmt.Sprintf("🏅 %d sat", amount)
userStr := GetUserStrMd(user)
tipmsg = fmt.Sprintf("%s (by %s)", tipmsg, userStr)
if notInitializedWallet {
tipmsg = tipmsg + fmt.Sprintf("\n🗑 Chat with %s to manage your wallet.", GetUserStrMd(bot.telegram.Me))
}
msg, err := bot.telegram.Reply(m.ReplyTo, tipmsg, tb.Silent)
if err != nil {
print(err)
}
message := NewMessage(msg, TipAmount(amount), Tips(1))
message.Tippers = appendUinqueUsersToSlice(message.Tippers, user)
bot.tips[m.ReplyTo.Sender.ID] = append(bot.tips[m.ReplyTo.Sender.ID], message)
}
// first call will return false, every following call will return true
return ok
}
-153
View File
@@ -1,153 +0,0 @@
package main
import (
"fmt"
"time"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
tb "gopkg.in/tucnak/telebot.v2"
)
type Transaction struct {
ID uint `gorm:"primarykey"`
Time time.Time `json:"time"`
Bot *TipBot `gorm:"-"`
From *tb.User `json:"from" gorm:"-"`
To *tb.User `json:"to" gorm:"-"`
FromId int `json:"from_id" `
ToId int `json:"to_id" `
FromUser string `json:"from_user"`
ToUser string `json:"to_user"`
Type string `json:"type"`
Amount int `json:"amount"`
ChatID int64 `json:"chat_id"`
ChatName string `json:"chat_name"`
Memo string `json:"memo"`
Success bool `json:"success"`
FromWallet string `json:"from_wallet"`
ToWallet string `json:"to_wallet"`
FromLNbitsID string `json:"from_lnbits"`
ToLNbitsID string `json:"to_lnbits"`
}
type transactionOption func(t *Transaction)
func TransactionChat(chat *tb.Chat) transactionOption {
return func(t *Transaction) {
t.ChatID = chat.ID
t.ChatName = chat.Title
}
}
func TransactionType(transactionType string) transactionOption {
return func(t *Transaction) {
t.Type = transactionType
}
}
func NewTransaction(bot *TipBot, from *tb.User, to *tb.User, amount int, opts ...transactionOption) *Transaction {
t := &Transaction{
Bot: bot,
From: from,
To: to,
FromUser: GetUserStr(from),
ToUser: GetUserStr(to),
FromId: from.ID,
ToId: to.ID,
Amount: amount,
Memo: "Powered by @LightningTipBot",
Time: time.Now(),
Success: false,
}
for _, opt := range opts {
opt(t)
}
return t
}
func (t *Transaction) Send() (success bool, err error) {
// maybe remove comments, GTP-3 dreamed this up but it's nice:
// if t.From.ID == t.To.ID {
// err = fmt.Errorf("Can not send transaction to yourself.")
// return false, err
// }
// todo: remove this commend if the backend is back up
success, err = t.SendTransaction(t.Bot, t.From, t.To, t.Amount, t.Memo)
// success = true
if success {
t.Success = success
// TODO: call post-send methods
}
// save transaction to db
tx := t.Bot.logger.Save(t)
if tx.Error != nil {
errMsg := fmt.Sprintf("Error: Could not log transaction: %s", err)
log.Errorln(errMsg)
}
return success, err
}
func (t *Transaction) SendTransaction(bot *TipBot, from *tb.User, to *tb.User, amount int, memo string) (bool, error) {
fromUserStr := GetUserStr(from)
toUserStr := GetUserStr(to)
// from := m.Sender
fromUser, err := GetUser(from, *bot)
if err != nil {
errmsg := fmt.Sprintf("[SendTransaction] Error: Could not get user %s", fromUserStr)
log.Errorln(errmsg)
return false, err
}
t.FromWallet = fromUser.Wallet.ID
t.FromLNbitsID = fromUser.ID
// check if fromUser has balance
balance, err := bot.GetUserBalance(from)
if err != nil {
errmsg := fmt.Sprintf("[SendTransaction] Error: Could not get balance of user %s", fromUserStr)
log.Errorln(errmsg)
return false, err
}
// check if fromUser has balance
if balance < amount {
errmsg := fmt.Sprintf("[SendTransaction] Error: User %s has not enough balance", fromUserStr)
bot.telegram.Send(from, fmt.Sprintf("🚫 Your balance is too low for that."))
log.Errorln(errmsg)
return false, fmt.Errorf(errmsg)
}
toUser, err := GetUser(to, *bot)
if err != nil {
errmsg := fmt.Sprintf("[SendTransaction] Error: ToUser %s not found: %s", toUserStr, err)
log.Errorln(errmsg)
return false, err
}
t.ToWallet = toUser.Wallet.ID
t.ToLNbitsID = toUser.ID
// generate invoice
invoice, err := toUser.Wallet.Invoice(
lnbits.InvoiceParams{
Amount: int64(amount),
Out: false,
Memo: memo},
*toUser.Wallet)
if err != nil {
errmsg := fmt.Sprintf("[SendTransaction] Error: Could not create invoice for user %s", toUserStr)
log.Errorln(errmsg)
return false, err
}
// pay invoice
_, err = fromUser.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoice.PaymentRequest}, *fromUser.Wallet)
if err != nil {
errmsg := fmt.Sprintf("[SendTransaction] Error: Payment from %s to %s of %d sat failed", fromUserStr, toUserStr, amount)
log.Errorln(errmsg)
return false, err
}
return true, err
}
+48
View File
@@ -0,0 +1,48 @@
# Translation guide
Thank you for helping to translate this bot into many different languages. If you chose to translate this bot, please try to test every possible case that you can think of. As time passes, new features will be added and your translation could become out of date. It would be great, if you could update your language's translation if you notice any weird changes.
## Quick and dirty summary
* Duplicate `en.toml` to your localization and edit string by string.
* Do not translate commands in the text! I.e. `/balance` stays `/balance`.
* Pay attention to every single `"""` and `%s` or `%d`.
* Your end result should have exactly the same number of lines as `en.toml`.
* Start sentences with `C`apital letters, end them with a full stop`.`
## General
* The bot checks the language settings of each Telegram user and translate the interaction with the user (private chats, **inline commands?**) to the user's language, if a translation is available. Otherwise, it will default to english. All messages in groups will be english. If the user does not have a language setting, it will default to english.
* For now, all `/commands` are in english. That means that all `/command` references in the help messages should remain english for now. We plan to implement localized commands, which is why you will find the strings in the translation files. Please chose simple, single-worded, lower-case, for the command translations.
* Please use a spell checker, like Google Docs to check your final translation. Thanks :)
## Language
* Please use a "kind" and "playful" tone in your translations. We do not have to be very dry and technical in tone. Please use a respectful language.
* Please remember who the prototypical user is: a non-technical fruit-selling lady in Brazil that wants to sell Mangos for Satoshis.
## Standards
* Please "fork" your translation from the english translation file `en.toml`. Simply copy the file, rename it to your language code (look it up on Google if you're unsure) and start editing :)
* Please use only "sat" as a denominator for amounts, do not use the plural form "sats".
* Please choose an appropriate expression for "Amount" and keep it across the entire translation.
* Please reuse all Emojis in the same location and order as the original text.
* Do not add line breaks. All translations should have the same number of lines.
* Please use english words for Bitcoin- and Lightning-native concepts like "Lightning", "Wallet", "Invoice", "Tip", and other technical terms like "Log", "Bot", etc. **IF** your language does not have a widely-used and recognized alternative for it. If most software in your language uses another word instead of "Wallet" for example, then we should also use that.
* For fixed english terms like "Tip" I recommend using the english version and giving a translation in parenthesis like "... Tips (*kleine Beträge*) senden kann". The text in *italic* is the next best translation of "Tips"
## Technical
* Every string should be wrapped in three quotes `"""`
* Strings can span over multiple lines.
* Every string variable found in the original english language file should be translated. If a specific string is missing in a translation, the english version will be used for that particular string.
* Every language has their own translation file. The file for english is `en.toml`.
* Headings to many sections are **bold** starting and ending with asterix `*`. Italic starts and ends with an underscore `_`.
* Command examples are in `code format` starting end ending with ``` ` ```
## Pleaceholders
* Symbols like `%s`, `%d`, `%f` are meant as placeholders for other bits of text, numbers, floats. Please reuse them in every string you translate.
* Please do not change the order of the placeholders in your translation. It would break things.
* Please do not use modifiers for **bold**, *italic*, and others around the placeholders. We are using MarkdownV1 and it would break things. Do not do `_%s_` for example.
## GitHub infos
* Please submit translations as a GitHub pull-request. This way, you can easily work with others and review each other. To submit a pull-request, you need a Github account. Then, fork the entire project (using the button in the upper-right corner).
* Then, create a new branch for your translation. Do this using the Github UI or via the terminal inside the project repository: `git checkout -b translation_es` for example. Then, create the appropriate language file and put it in the translations folder. Then, add it to the branch with by navigating to the translations folder `git add es.toml` and `git commit -m 'add spanish'`. Finally, push the branch to your fork `git push --set-upstream origin translation_es`. When done, open a pull-request in the *original github repo* and select your forked branch.
* Good luck :)
+297
View File
@@ -0,0 +1,297 @@
# 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"""
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. Es ist offen für jeden, dezentral und es gibt niemanden, der Bitcoin kontrolliert. Bitcoin ist hartes Geld, was 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. Empfholene Lightning Wallets für dein Handy sind _ [Phoenix](https://phoenix.acinq.co/)_,_ [Breez](https://breez.technology/)_,_ [Muun](https://muun.com/)_ (non-custodial), or_ [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 Verwalter 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 = """👋 Bitte setze einen Telegram Benutzernamen."""
advancedMessage = """%s
👉 *Inline Befehle*
*send* 💸 Sende sats an einen Chat: `%s send <betrag> [<memo>]`
*receive* 🏅 Bitte um Zahlung: `%s receive <betrag> [<memo>]`
*faucet* 🚰 Erzeuge einen Zapfhahn: `%s faucet <gesamt> <pro_user>`
📖 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>`"""
# START
startSettingWalletMessage = """🧮 Richte dein Wallet ein..."""
startWalletCreatedMessage = """🧮 Wallet erstellt."""
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 <amount> [<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."""
lnurlEnterAmountMessage = """⌨️ Gebe einen Betrag zwischen %d und %d sat ein."""
lnurlHelpText = """📖 Ups, das hat nicht geklappt. %s
*Befehl:* `/lnurl [betrag] <lnurl>`
*Beispiel:* `/lnurl LNURL1DP68GUR...`"""
# 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:* Kiere 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 = """Erzuge einen Zapfhahn in einer Gruppe, wo der Bot eingeladen ist oder benutze einen 👉 Inline Bommand (/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> [<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> [<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."""
+297
View File
@@ -0,0 +1,297 @@
# 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"""
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"""
# 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> [<memo>]`
*receive* 🏅 Request a payment: `%s receive <amount> [<memo>]`
*faucet* 🚰 Create a faucet: `%s faucet <capacity> <per_user>`
📖 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>`"""
# 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."""
lnurlEnterAmountMessage = """⌨️ Enter an amount between %d and %d sat."""
lnurlHelpText = """📖 Oops, that didn't work. %s
*Usage:* `/lnurl [amount] <lnurl>`
*Example:* `/lnurl LNURL1DP68GUR...`"""
# 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."""
# 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> [<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> [<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."""
+297
View File
@@ -0,0 +1,297 @@
# 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 = """bote"""
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> [<memo>]`
*receive* 🏅 Solicita un pago: `%s receive <monto> [<memo>]`.
*faucet* 🚰 Crear un grifo: `%s faucet <capacidad> <por_usuario>`.
📖 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: `%s faucet <capacidad> <por_usuario>`"""
# START
startSettingWalletMessage = """🧮 Configurar 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."""
lnurlEnterAmountMessage = """⌨️ Introduce un monto entre %d y %d sat."""
lnurlHelpText = """📖 Oops, eso no funcionó. %s
*Uso:* `/lnurl [monto] <lnurl>`
*Ejemplo:* `/lnurl LNURL1DP68GUR...`"""
# 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> [<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> [<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."""
+297
View File
@@ -0,0 +1,297 @@
# 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> [<memo>]`
*receive* 🏅 Demander un paiement : `%s receive <montant> [<memo>]`
*faucet* 🚰 Créer un faucet: `%s faucet <capacité> <par_utilisateur>`
📖 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>`"""
# 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."""
lnurlEnterAmountMessage = """⌨️ Choisissez un montant entre %d et %d sat."""
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> [<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> [<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."""
+297
View File
@@ -0,0 +1,297 @@
# 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> [<descrizione>]`
*/balance* 👑 Verifica il tuo saldo residuo: `/balance`
*/send* 💸 Invia fondi a un utente: `/send <ammontare> @utente o utente@ln.tips [<descrizione>]`
*/invoice* ⚡️ Ricevi attraverso Lightning: `/invoice <ammontare> [<descrizione>]`
*/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> [<descrizione>]`
*receive* 🏅 Richiedi un pagamento: `%s receive <ammontare> [<descrizione>]`
*faucet* 🚰 Eroga fondi ai partecipanti della chat: `%s faucet <ammontare_totale> <per_utente>`
📖 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* 🚰 Eroga fondi ai partecipanti della chat `/faucet <ammontare_totale> <per_utente>`"""
# 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> [<descrizione>]`
*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> [<descrizione>]`
*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> [<descrizione>]`
*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."""
lnurlEnterAmountMessage = """⌨️ Imposta un ammontare tra %d e %d sat."""
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 <ammontare_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 <ammontare_totale> <per_utente>`
*Esempio:* `/faucet 210 21`"""
# INLINE SEND
inlineQuerySendTitle = """💸 Invia pagamento in una chat."""
inlineQuerySendDescription = """Sintassi: @%s send <ammontare> [<descrizione>]"""
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> [<descrizione>]"""
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."""
+297
View File
@@ -0,0 +1,297 @@
# 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> [<memo>]`
*receive* 🏅 Verzoek om betaling: `%s receive <bedrag> [<memo>]`
*faucet* 🚰 Maak een kraan: `%s faucet <capacity> <per_user>`
📖 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>`"""
# 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."""
lnurlEnterAmountMessage = """⌨️ Voer een bedrag in tussen %d en %d sat."""
lnurlHelpText = """📖 Oeps, dat werkte niet. %s
*Usage:* `/lnurl [bedrag] <lnurl>`
*Example:* `/lnurl LNURL1DP68GUR...`"""
# 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> [<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> [<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."""
+297
View File
@@ -0,0 +1,297 @@
# 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> [<memo>]`
*receive* 🏅 Solicite um pagamento: `%s receive <quantidade> [<memo>]`.
*faucet* 🚰 Criar uma torneira: `%s faucet <capacidade> <por_usuário>`.
📖 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: `%s faucet <capacidade> <por_usuário>`"""
# 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."""
lnurlEnterAmountMessage = """⌨️ Insira uma quantia entre %d e %d sat."""
lnurlHelpText = """📖 Opa, isso não funcionou. %s
*Uso:* `/lnurl [quantidade] <lnurl>`
*Exemplo:* `/lnurl LNURL1DP68GUR...`"""
# 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> [<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> [<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."""