Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
249b71fc06 | ||
|
|
0a136da5f9 | ||
|
|
e169dc676d | ||
|
|
90ccdc775c | ||
|
|
6aa95bb280 | ||
|
|
299164bf05 | ||
|
|
0c45c4d8c0 | ||
|
|
fc45f6df68 | ||
|
|
794c2503e4 | ||
|
|
839b535b73 | ||
|
|
cb36e84216 | ||
|
|
998ed1db58 | ||
|
|
77c3a50c0c | ||
|
|
f3b3e3440b | ||
|
|
23785a650c | ||
|
|
d31e621720 | ||
|
|
cae8df6557 | ||
|
|
90ebd90d59 | ||
|
|
64c1bf1aa3 | ||
|
|
8d4b0a5f65 | ||
|
|
985952de00 | ||
|
|
3fe903bc51 | ||
|
|
4bf0e05d6c | ||
|
|
3317cf09e1 | ||
|
|
13759ff048 | ||
|
|
827bfb108d | ||
|
|
e2017ecfe9 | ||
|
|
059cb5cdd8 | ||
|
|
80d0ec57b1 | ||
|
|
790f0943cc | ||
|
|
4af2ca8799 | ||
|
|
323fd14c9e |
@@ -4,9 +4,9 @@
|
||||
|
||||
# @LightningTipBot 🏅
|
||||
|
||||
A tip bot and Lightning ⚡️ Bitcoin Wallet for Telegram group chats. It can also be used as a personal Lightning wallet by anyone who has a Telegram account.
|
||||
A Telegram Lightning ⚡️ Bitcoin wallet and tip bot for group chats.
|
||||
|
||||
This repository contains everything you need to set up and run your own tip bot. If you simply want to use this bot in your group chat without having to install anything just start a conversation with [@LightningTipBot](https://t.me/LightningTipBot) and invite it into your chat.
|
||||
This repository contains everything you need to set up and run your own tip bot. If you simply want to use this bot in your group chat without having to install anything just start a conversation with [@LightningTipBot](https://t.me/LightningTipBot) and invite it into your group chat.
|
||||
|
||||
## Setting up the bot
|
||||
|
||||
@@ -21,9 +21,7 @@ go build .
|
||||
cp config.yaml-example config.yaml
|
||||
```
|
||||
|
||||
Alternatively, you can download binary releases [here](https://github.com/LightningTipBot/LightningTipBot/releases) **(note: no realses yet)**.
|
||||
|
||||
After you have configured the bot, start it using the command
|
||||
After the configuration (see below), start it using the command
|
||||
|
||||
```
|
||||
./LightningTipBot
|
||||
@@ -54,23 +52,35 @@ 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.
|
||||
- `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).
|
||||
- `lnbits_public_url` is the public URL of your lnbits/LndHub (for BlueWallet/Zap support, optional).
|
||||
- `lnurl_public_server` is used 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.
|
||||
/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>
|
||||
```
|
||||
|
||||
### Live tooltips
|
||||
@@ -81,6 +91,30 @@ The bot replies to a tipped message to indicate to all participants how many and
|
||||
<img alt="How to set up a lnbits wallet and the User Manager extension." src="resources/tooltips.png" >
|
||||
</p>
|
||||
|
||||
### LNURL server
|
||||
|
||||
Users can send and receive via . For this to work, you need to set the `lnurl_public_server` in `config.yaml`. The bot will then host a LNURL endpoint at `.well-known/lnurlp/username` which handles the data exchange with other wallets. You can set `http_proxy` in `config.yaml` to send outbound requests only via an HTTP proxy.
|
||||
|
||||
### Send and receive via Lightning Address
|
||||
|
||||
Every user has a [Lightning Address](https://lightningaddress.com/) a la `username@host.com` with which they can send to via `/send <amount> <user@domain.com>` and receive from other wallets.
|
||||
|
||||
### Link to BlueWallet or Zap
|
||||
|
||||
Every user can link their wallet to an external app like [Bluewallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/) by using the command `/link`. If you host the bot, you will have to enable the LndHub extension in LNbits. You also need to edit the `lnbits_public_url` entry in `config.yaml` accordingly to an address that can be reached by the user's wallet (Tor should be fine as well).
|
||||
|
||||
<p align="center">
|
||||
<img alt="QR code payment example." src="resources/lndhub.png" >
|
||||
</p>
|
||||
|
||||
### Pay invoices by sending QR codes
|
||||
|
||||
To pay a Lightning invoice, you can snap a photo of a QR code and send it directly to the bot. Note that you might need to zoom in, center the QR code, or crop the image if the bot fails to decode the QR code from the photo. By the way, you can also just send an the invoice as a string, the bot will automatically detect it and initiate a payment.
|
||||
|
||||
<p align="center">
|
||||
<img alt="QR code payment example." src="resources/qr_code_example.jpg" >
|
||||
</p>
|
||||
|
||||
### Auto-delete commands
|
||||
|
||||
To minimize the clutter all the heavy tipping can cause in a group chat, the bot will remove all failed commands (for example due to a syntax error) from the chat immediately. All successful commands will stay visible for `message_dispose_duration` seconds (default 10s) and then be removed. The tips will sill be visible for everyone in the Live tooltip. This feature only works, if the bot is made admin of the group.
|
||||
@@ -91,3 +125,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.
|
||||
|
||||
+2
-1
@@ -9,7 +9,8 @@ import (
|
||||
)
|
||||
|
||||
func (bot TipBot) balanceHandler(m *tb.Message) {
|
||||
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
// reply only in private message
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
@@ -76,16 +78,20 @@ 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,
|
||||
tb.OnPhoto: bot.privatePhotoHandler,
|
||||
tb.OnText: bot.anyTextHandler,
|
||||
"/tip": bot.tipHandler,
|
||||
"/pay": bot.confirmPaymentHandler,
|
||||
"/invoice": bot.invoiceHandler,
|
||||
"/balance": bot.balanceHandler,
|
||||
"/start": bot.startHandler,
|
||||
"/send": bot.confirmSendHandler,
|
||||
"/help": bot.helpHandler,
|
||||
"/basics": bot.basicsHandler,
|
||||
"/donate": bot.donationHandler,
|
||||
"/advanced": bot.advancedHelpHandler,
|
||||
"/link": bot.lndhubHandler,
|
||||
"/lnurl": bot.lnurlHandler,
|
||||
tb.OnPhoto: bot.privatePhotoHandler,
|
||||
tb.OnText: bot.anyTextHandler,
|
||||
}
|
||||
// assign handler to endpoint
|
||||
for endpoint, handler := range endpointHandler {
|
||||
@@ -106,6 +112,7 @@ func (bot TipBot) registerTelegramHandlers() {
|
||||
// for /send
|
||||
bot.telegram.Handle(&btnSend, bot.sendHandler)
|
||||
bot.telegram.Handle(&btnCancelSend, bot.cancelSendHandler)
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
@@ -123,5 +130,7 @@ func (bot TipBot) Start() {
|
||||
}
|
||||
bot.registerTelegramHandlers()
|
||||
lnbits.NewWebhook(Configuration.WebhookServer, bot.telegram, bot.client, bot.database)
|
||||
lnurl.NewServer(Configuration.LNURLServer, Configuration.WebhookServer, bot.telegram, bot.client, bot.database)
|
||||
|
||||
bot.telegram.Start()
|
||||
}
|
||||
|
||||
@@ -6,8 +6,10 @@
|
||||
4 - Paste this:
|
||||
|
||||
help - Read the help.
|
||||
balance - Check your balance.
|
||||
tip - Reply to a message to tip it.
|
||||
send - Send funds to a user.
|
||||
invoice - Create a Lightning invoice to receive payments.
|
||||
pay - Pay a Lightning invoice.
|
||||
balance - Check balance.
|
||||
tip - Reply to a message to tip. Example: /tip 50
|
||||
send - Send funds to a user. Example: /send 100 @LightningTipBot
|
||||
invoice - Receive with Lightning. Example: /invoice 1000
|
||||
pay - Pay with Lightning. Example: /pay lnbc10n1ps...
|
||||
donate - Donate: Example: /donate 1000
|
||||
advanced - Advanced help
|
||||
@@ -6,8 +6,11 @@ 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"`
|
||||
LNURLServer string `json:"lnurl_public_server" yaml:"lnurl_public_server"`
|
||||
ApiKey string `json:"telegram_api_key" yaml:"telegram_api_key"`
|
||||
HttpProxy string `json:"http_proxy" yaml:"http_proxy"`
|
||||
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"`
|
||||
|
||||
+5
-2
@@ -1,6 +1,9 @@
|
||||
telegram_api_key: "1234"
|
||||
webhook_server: "http://0.0.0.0:1234"
|
||||
lnbits_url: "http://*.onion:1234"
|
||||
webhook_server: "http://0.0.0.0:5588"
|
||||
lnbits_url: "http://127.0.0.1:5000"
|
||||
http_proxy: "http://127.0.0.1:8118"
|
||||
lnbits_public_url: "http://url.com:5000"
|
||||
lnurl_public_server: "http://url.com:80"
|
||||
lnbits_admin_key: "1234"
|
||||
lnbits_admin_id: "3212"
|
||||
db_path: "data/bot.db"
|
||||
|
||||
+4
-2
@@ -49,9 +49,10 @@ func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
}()
|
||||
var err error
|
||||
go func() {
|
||||
if !reflect.DeepEqual(u, user.Telegram) {
|
||||
u_cp := bot.copyLowercaseUser(u)
|
||||
if !reflect.DeepEqual(u_cp, user.Telegram) {
|
||||
// update possibly changed user details in database
|
||||
user.Telegram = u
|
||||
user.Telegram = u_cp
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
log.Warnln(fmt.Sprintf("[UpdateUserRecord] %s", err.Error()))
|
||||
@@ -62,6 +63,7 @@ func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
}
|
||||
|
||||
func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
|
||||
user.Telegram = bot.copyLowercaseUser(user.Telegram)
|
||||
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))
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
// PLEASE DO NOT CHANGE THE CODE IN THIS FILE
|
||||
// YOU MIGHT BREAK DONATIONS TO THE ORIGINAL PROJECT
|
||||
// THE DEVELOPMENT OF LIGHTNINGTIPBOT RELIES ON DONATIONS
|
||||
// IF YOU USE THIS PROJECT, LEAVE THIS CODE ALONE
|
||||
|
||||
var (
|
||||
donationSuccess = "🙏 Thank you for your donation."
|
||||
donationErrorMessage = "🚫 Oh no. Donation failed."
|
||||
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\n\n" +
|
||||
"*Usage:* `/donate <amount>`\n" +
|
||||
"*Example:* `/donate 1000`"
|
||||
endpoint string
|
||||
)
|
||||
|
||||
func helpDonateUsage(errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(donateHelpText, fmt.Sprintf("%s", errormsg))
|
||||
} else {
|
||||
return fmt.Sprintf(donateHelpText, "")
|
||||
}
|
||||
}
|
||||
|
||||
func (bot TipBot) donationHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
|
||||
if len(strings.Split(m.Text, " ")) < 2 {
|
||||
bot.telegram.Send(m.Sender, helpDonateUsage(donateEnterAmountMessage))
|
||||
return
|
||||
}
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if amount < 1 {
|
||||
bot.telegram.Send(m.Sender, helpDonateUsage(donateValidAmountMessage))
|
||||
return
|
||||
}
|
||||
|
||||
// command is valid
|
||||
msg, _ := bot.telegram.Send(m.Sender, donationProgressMessage)
|
||||
// get invoice
|
||||
resp, err := http.Get(fmt.Sprintf(endpoint, amount, GetUserStr(m.Sender), GetUserStr(bot.telegram.Me)))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.telegram.Edit(msg, donationErrorMessage)
|
||||
return
|
||||
}
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.telegram.Edit(msg, donationErrorMessage)
|
||||
return
|
||||
}
|
||||
|
||||
// send donation invoice
|
||||
user, err := GetUser(m.Sender, bot)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// bot.telegram.Send(user.Telegram, string(body))
|
||||
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: string(body)}, *user.Wallet)
|
||||
if err != nil {
|
||||
userStr := GetUserStr(m.Sender)
|
||||
errmsg := fmt.Sprintf("[/donate] Donation failed for user %s: %s", userStr, err)
|
||||
log.Errorln(errmsg)
|
||||
bot.telegram.Edit(msg, fmt.Sprintf(donationFailedMessage, err))
|
||||
return
|
||||
}
|
||||
bot.telegram.Edit(msg, 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)
|
||||
}
|
||||
endpoint = sb.String()
|
||||
}
|
||||
|
||||
type rot13Reader struct {
|
||||
r io.Reader
|
||||
}
|
||||
|
||||
func (rot13 rot13Reader) Read(b []byte) (int, error) {
|
||||
n, err := rot13.r.Read(b)
|
||||
for i := 0; i < n; i++ {
|
||||
switch {
|
||||
case b[i] >= 65 && b[i] <= 90:
|
||||
if b[i] <= 77 {
|
||||
b[i] = b[i] + 13
|
||||
} else {
|
||||
b[i] = b[i] - 13
|
||||
}
|
||||
case b[i] >= 97 && b[i] <= 122:
|
||||
if b[i] <= 109 {
|
||||
b[i] = b[i] + 13
|
||||
} else {
|
||||
b[i] = b[i] - 13
|
||||
}
|
||||
}
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (bot TipBot) parseCmdDonHandler(m *tb.Message) error {
|
||||
arg := ""
|
||||
if strings.HasPrefix(strings.ToLower(m.Text), "/send") {
|
||||
arg, _ = getArgumentFromCommand(m.Text, 2)
|
||||
if arg != "@"+bot.telegram.Me.Username {
|
||||
return fmt.Errorf("err")
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(strings.ToLower(m.Text), "/tip") {
|
||||
arg = GetUserStr(m.ReplyTo.Sender)
|
||||
if arg != "@"+bot.telegram.Me.Username {
|
||||
return fmt.Errorf("err")
|
||||
}
|
||||
}
|
||||
if arg == "@LightningTipBot" || len(arg) < 1 {
|
||||
return fmt.Errorf("err")
|
||||
}
|
||||
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
_, err = io.Copy(&sb, rot13Reader{strings.NewReader("Gunax lbh! V'z ebhgvat guvf qbangvba gb YvtugavatGvcObg@ya.gvcf.")})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
donationInterceptMessage := sb.String()
|
||||
|
||||
bot.telegram.Send(m.Sender, MarkdownEscape(donationInterceptMessage))
|
||||
m.Text = fmt.Sprintf("/donate %d", amount)
|
||||
bot.donationHandler(m)
|
||||
// returning nil here will abort the parent handler (/pay or /tip)
|
||||
return nil
|
||||
}
|
||||
@@ -3,6 +3,7 @@ module github.com/LightningTipBot/LightningTipBot
|
||||
go 1.15
|
||||
|
||||
require (
|
||||
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
|
||||
@@ -11,6 +12,7 @@ require (
|
||||
github.com/makiuchi-d/gozxing v0.0.2
|
||||
github.com/sirupsen/logrus v1.2.0
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||
github.com/tidwall/gjson v1.6.1
|
||||
gopkg.in/tucnak/telebot.v2 v2.3.5
|
||||
gorm.io/driver/sqlite v1.1.4
|
||||
gorm.io/gorm v1.21.12
|
||||
|
||||
@@ -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=
|
||||
@@ -196,9 +198,13 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
|
||||
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/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/match v1.0.1 h1:PnKP62LPNxHKTwvHHZZzdOAOCtsJTjo6dZLCwpKm5xc=
|
||||
github.com/tidwall/match v1.0.1/go.mod h1:LujAq0jyVjBy028G1WhWfIzbpQfMO8bBZ6Tyb0+pL9E=
|
||||
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/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=
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"fmt"
|
||||
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
helpMessage = "ℹ️ *Info*\n_This bot sends Bitcoin tips on the Lightning Network⚡️. The basic unit of tips are Satoshis (sat). 100,000,000 sat = 1 Bitcoin. There will only ever be 21 Million Bitcoin._\n\n" +
|
||||
helpMessage = "⚡️ *Wallet*\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. Type 📚 /basics for more._\n\n" +
|
||||
"❤️ *Donate*\n" +
|
||||
"_This bot charges no fees but generates costs. If you like to support this bot, please consider a donation. To donate, just tip @LightningTipBot or try_ `/send 1000 @LightningTipBot`\n\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" +
|
||||
"%s" +
|
||||
"⚙️ *Commands*\n" +
|
||||
"*/tip* 🏅 Reply to a message to tip it: `/tip <amount> [<memo>]`\n" +
|
||||
"*/tip* 🏅 Reply to a message to tip: `/tip <amount> [<memo>]`\n" +
|
||||
"*/balance* 👑 Check your balance: `/balance`\n" +
|
||||
"*/send* 💸 Send funds to a user: `/send <amount> <@username> [<memo>]`\n" +
|
||||
"*/invoice* ⚡️ Receive over Lightning: `/invoice <amount> [<memo>]`\n" +
|
||||
"*/pay* ⚡️ Pay over Lightning: `/pay <invoice>`\n" +
|
||||
"*/help* 📖 Read this help (more: */info*).\n"
|
||||
"*/send* 💸 Send funds to a user: `/send <amount> @user or user@ln.tips [<memo>]`\n" +
|
||||
"*/invoice* ⚡️ Receive with Lightning: `/invoice <amount> [<memo>]`\n" +
|
||||
"*/pay* ⚡️ Pay with Lightning: `/pay <invoice>`\n" +
|
||||
"*/donate* ❤️ Donate to the project: `/donate 1000`\n" +
|
||||
"*/advanced* 🤖 Advanced features.\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" +
|
||||
@@ -24,27 +28,56 @@ const (
|
||||
"⚡️ *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. If you don't have a Lightning wallet yet, check out_ [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" +
|
||||
"_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. You don't have to trust anyone to keep your funds safe._\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" +
|
||||
"_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. 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._\n\n" +
|
||||
"❤️ *Donate*\n" +
|
||||
"_This bot charges no fees but generates costs. If you like to support this bot, please consider a donation. To donate, just tip @LightningTipBot or try_ `/send 1000 @LightningTipBot`"
|
||||
"_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\n\n" + "⚙️ *Advanced commands*\n" +
|
||||
"*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)\n" +
|
||||
"*/lnurl* ⚡️ Lnurl receive or pay: `/lnurl` or `/lnurl <lnurl>`\n"
|
||||
)
|
||||
|
||||
func (bot TipBot) makeHelpMessage(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\n", helpNoUsernameMessage)
|
||||
} else {
|
||||
dynamicHelpMessage = "ℹ️ *Info*\n"
|
||||
lnaddr, err := bot.UserGetLightningAddress(m.Sender)
|
||||
if err != nil {
|
||||
dynamicHelpMessage = ""
|
||||
} else {
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Your Lightning Address is `%s`\n", lnaddr)
|
||||
}
|
||||
}
|
||||
dynamicHelpMessage = dynamicHelpMessage + "\n"
|
||||
return fmt.Sprintf(helpMessage, dynamicHelpMessage)
|
||||
}
|
||||
|
||||
func (bot TipBot) helpHandler(m *tb.Message) {
|
||||
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
|
||||
// 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)
|
||||
bot.telegram.Send(m.Sender, bot.makeHelpMessage(m), tb.NoPreview)
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) infoHandler(m *tb.Message) {
|
||||
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
|
||||
func (bot TipBot) basicsHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
if !m.Private() {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
@@ -52,3 +85,40 @@ func (bot TipBot) infoHandler(m *tb.Message) {
|
||||
bot.telegram.Send(m.Sender, infoMessage, tb.NoPreview)
|
||||
return
|
||||
}
|
||||
|
||||
func (bot TipBot) makeadvancedHelpMessage(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", 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 := bot.UserGetLNURL(m.Sender)
|
||||
if err != nil {
|
||||
dynamicHelpMessage = ""
|
||||
} else {
|
||||
dynamicHelpMessage = dynamicHelpMessage + fmt.Sprintf("Your LNURL:\n`%s`", lnurl)
|
||||
}
|
||||
|
||||
}
|
||||
return fmt.Sprintf(advancedMessage, dynamicHelpMessage)
|
||||
}
|
||||
|
||||
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, bot.makeadvancedHelpMessage(m), tb.NoPreview)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -26,6 +26,8 @@ type UserStateKey int
|
||||
const (
|
||||
UserStateConfirmPayment = iota + 1
|
||||
UserStateConfirmSend
|
||||
UserStateLNURLEnterAmount
|
||||
UserStateConfirmLNURLPay
|
||||
)
|
||||
|
||||
func (u *User) ResetState() {
|
||||
@@ -34,10 +36,11 @@ func (u *User) ResetState() {
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
invoiceReceivedMessage = "⚡️ You've received %d sat."
|
||||
invoiceReceivedMessage = "⚡️ You received %d sat."
|
||||
)
|
||||
|
||||
type WebhookServer struct {
|
||||
@@ -32,7 +32,7 @@ func NewWebhook(webhookServer string, bot *tb.Bot, client *Client, database *gor
|
||||
if !strings.Contains(webhookServer, "://") {
|
||||
log.Fatal("invalid webhook server configuration. please add a scheme.")
|
||||
}
|
||||
_, port, err := net.SplitHostPort(strings.Split(webhookServer, "//")[1])
|
||||
host, port, err := net.SplitHostPort(strings.Split(webhookServer, "//")[1])
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -50,6 +50,7 @@ func NewWebhook(webhookServer string, bot *tb.Bot, client *Client, database *gor
|
||||
}
|
||||
apiServer.httpServer.Handler = apiServer.newRouter()
|
||||
go apiServer.httpServer.ListenAndServe()
|
||||
log.Infof("[Webhook] Server started at %s port %s", host, port)
|
||||
return apiServer
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
package lnurl
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/fiatjaf/go-lnurl"
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
httpServer *http.Server
|
||||
bot *tb.Bot
|
||||
c *lnbits.Client
|
||||
database *gorm.DB
|
||||
callbackUrl string
|
||||
WebhookServer string
|
||||
}
|
||||
|
||||
const (
|
||||
lnurlEndpoint = "/.well-known/lnurlp"
|
||||
minSendable = 1000 // mSat
|
||||
MaxSendable = 1000000000
|
||||
)
|
||||
|
||||
func NewServer(lnurlserver string, webhookserver string, bot *tb.Bot, client *lnbits.Client, database *gorm.DB) *Server {
|
||||
host, port, err := net.SplitHostPort(strings.Split(lnurlserver, "//")[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 := &Server{
|
||||
c: client,
|
||||
database: database,
|
||||
bot: bot,
|
||||
httpServer: srv,
|
||||
callbackUrl: host,
|
||||
WebhookServer: webhookserver,
|
||||
}
|
||||
|
||||
apiServer.httpServer.Handler = apiServer.newRouter()
|
||||
go apiServer.httpServer.ListenAndServe()
|
||||
log.Infof("[LNURL] Server started at %s port %s", host, port)
|
||||
return apiServer
|
||||
}
|
||||
|
||||
func (w *Server) newRouter() *mux.Router {
|
||||
router := mux.NewRouter()
|
||||
router.HandleFunc(lnurlEndpoint+"/{username}", w.handleLnUrl).Methods(http.MethodGet)
|
||||
router.HandleFunc("/@{username}", w.handleLnUrl).Methods(http.MethodGet)
|
||||
//router.HandleFunc("/.well-know/lnurlp/{username}", w.handleLnUrl).Methods(http.MethodGet)
|
||||
return router
|
||||
}
|
||||
|
||||
func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.URL.RawQuery == "" {
|
||||
var err error
|
||||
err = w.serveLNURLpFirst(writer, request)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
w.serveLNURLpSecond(writer, request)
|
||||
}
|
||||
}
|
||||
|
||||
// descriptionHash is the SHA256 hash of the metadata
|
||||
func (w Server) descriptionHash(metadata lnurl.Metadata, writer http.ResponseWriter) string {
|
||||
jsonMeta, err := json.Marshal(metadata)
|
||||
if err != nil {
|
||||
writer.WriteHeader(400)
|
||||
return ""
|
||||
}
|
||||
hash := sha256.Sum256([]byte(string(jsonMeta)))
|
||||
hash_string := hex.EncodeToString(hash[:])
|
||||
return hash_string
|
||||
}
|
||||
|
||||
// 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(request *http.Request) lnurl.Metadata {
|
||||
vars := mux.Vars(request)
|
||||
return lnurl.Metadata{{"text/identifier", fmt.Sprintf("%s@ln.tips", vars["username"])}, {"text/plain", fmt.Sprintf("Pay to %s@%s", vars["username"], w.callbackUrl)}}
|
||||
}
|
||||
|
||||
// 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(writer http.ResponseWriter, request *http.Request) error {
|
||||
vars := mux.Vars(request)
|
||||
|
||||
callback := fmt.Sprintf("%s%s/%s", w.callbackUrl, lnurlEndpoint, vars["username"])
|
||||
callbackURL, err := url.Parse(callback)
|
||||
if err != nil {
|
||||
log.Errorln("callback is not a valid URL")
|
||||
writer.WriteHeader(400)
|
||||
return err
|
||||
}
|
||||
metadata := w.metaData(request)
|
||||
jsonMeta, err := json.Marshal(metadata)
|
||||
if err != nil {
|
||||
writer.WriteHeader(400)
|
||||
return err
|
||||
}
|
||||
|
||||
resp := lnurl.LNURLPayResponse1{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: "OK"},
|
||||
Tag: "payRequest",
|
||||
Callback: fmt.Sprintf("https://%s", callback),
|
||||
CallbackURL: callbackURL,
|
||||
MinSendable: minSendable,
|
||||
MaxSendable: MaxSendable,
|
||||
EncodedMetadata: string(jsonMeta),
|
||||
}
|
||||
jsonResponse, err := json.Marshal(resp)
|
||||
if err != nil {
|
||||
writer.WriteHeader(400)
|
||||
return err
|
||||
}
|
||||
writer.WriteHeader(200)
|
||||
writer.Write(jsonResponse)
|
||||
return nil
|
||||
}
|
||||
|
||||
// serveLNURLpSecond serves the second LNURL response with the payment request with the correct description hash
|
||||
func (w Server) serveLNURLpSecond(writer http.ResponseWriter, request *http.Request) {
|
||||
vars := mux.Vars(request)
|
||||
user := &lnbits.User{}
|
||||
tx := w.database.Where("telegram_username = ?", strings.ToLower(vars["username"])).First(user)
|
||||
if tx.Error != nil || user.Wallet == nil || user.Initialized == false {
|
||||
errmsg := fmt.Sprintf("[GetUser] Couldn't fetch user info from database.")
|
||||
log.Warnln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// set wallet lnbits client
|
||||
user.Wallet.Client = w.c
|
||||
stringAmount := request.FormValue("amount")
|
||||
amount, err := strconv.Atoi(stringAmount)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[serveLNURLpSecond] Couldn't cast amount to int")
|
||||
log.Warnln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
var resp lnurl.LNURLPayResponse2
|
||||
|
||||
if amount < minSendable || amount > MaxSendable {
|
||||
// amount is not ok
|
||||
errmsg := fmt.Sprintf("[serveLNURLpSecond] Amount out of bounds")
|
||||
log.Warnln(errmsg)
|
||||
resp = lnurl.LNURLPayResponse2{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: "ERROR", Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", minSendable, MaxSendable)},
|
||||
}
|
||||
} else {
|
||||
// amount is ok
|
||||
|
||||
// the same description_hash needs to be built in the second request
|
||||
metadata := w.metaData(request)
|
||||
hash_string := w.descriptionHash(metadata, writer)
|
||||
invoice, err := user.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Amount: int64(amount / 1000),
|
||||
Out: false,
|
||||
DescriptionHash: hash_string,
|
||||
Webhook: w.WebhookServer},
|
||||
*user.Wallet)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[serveLNURLpSecond] Couldn't create invoice: %s", err.Error())
|
||||
log.Warnln(errmsg)
|
||||
resp = lnurl.LNURLPayResponse2{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: "ERROR", Reason: "Couldn't create invoice."},
|
||||
}
|
||||
} else {
|
||||
resp = lnurl.LNURLPayResponse2{
|
||||
LNURLResponse: lnurl.LNURLResponse{Status: "OK"},
|
||||
PR: invoice.PaymentRequest,
|
||||
Routes: make([][]lnurl.RouteInfo, 0),
|
||||
SuccessAction: &lnurl.SuccessAction{Message: "Payment received!", Tag: "message"},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
jsonResponse, err := json.Marshal(resp)
|
||||
if err != nil {
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
writer.Write(jsonResponse)
|
||||
}
|
||||
+13
-7
@@ -12,26 +12,32 @@ import (
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func helpInvoiceUsage(errormsg string) string {
|
||||
helpstr := "📖 Oops, that didn't work. %s\n\n" +
|
||||
const (
|
||||
invoiceEnterAmountMessage = "Did you enter an amount?"
|
||||
invoiceValidAmountMessage = "Did you enter a valid amount?"
|
||||
invoiceHelpText = "📖 Oops, that didn't work. %s\n\n" +
|
||||
"*Usage:* `/invoice <amount> [<memo>]`\n" +
|
||||
"*Example:* `/invoice 1000 Take this! 💸`"
|
||||
)
|
||||
|
||||
func helpInvoiceUsage(errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
helpstr = fmt.Sprintf(helpstr, fmt.Sprintf("_%s_", errormsg))
|
||||
return fmt.Sprintf(invoiceHelpText, fmt.Sprintf("%s", errormsg))
|
||||
} else {
|
||||
helpstr = fmt.Sprintf(helpstr, "")
|
||||
return fmt.Sprintf(invoiceHelpText, "")
|
||||
}
|
||||
return helpstr
|
||||
}
|
||||
|
||||
func (bot TipBot) invoiceHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
return
|
||||
}
|
||||
if len(strings.Split(m.Text, " ")) < 2 {
|
||||
bot.telegram.Send(m.Sender, helpInvoiceUsage(""))
|
||||
bot.telegram.Send(m.Sender, helpInvoiceUsage(invoiceEnterAmountMessage))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -43,7 +49,7 @@ func (bot TipBot) invoiceHandler(m *tb.Message) {
|
||||
}
|
||||
if amount > 0 {
|
||||
} else {
|
||||
bot.telegram.Send(m.Sender, helpInvoiceUsage("Did you use a valid amount?"))
|
||||
bot.telegram.Send(m.Sender, helpInvoiceUsage(invoiceValidAmountMessage))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
walletConnectMessage = "🔗 *Link your wallet*\n\n" +
|
||||
"⚠️ Never share the URL or the QR code with anyone or they will be able to access your funds.\n\n" +
|
||||
"- *BlueWallet:* Press *New wallet*, *Import wallet*, *Scan or import a file*, and scan the QR code.\n" +
|
||||
"- *Zeus:* Copy the URL below, press *Add a new node*, *Import* (the URL), *Save Node Config*."
|
||||
)
|
||||
|
||||
func (bot TipBot) lndhubHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
// reply only in private message
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
}
|
||||
// first check whether the user is initialized
|
||||
fromUser, err := GetUser(m.Sender, bot)
|
||||
if err != nil {
|
||||
log.Errorf("[/balance] Error: %s", err)
|
||||
return
|
||||
}
|
||||
bot.telegram.Send(m.Sender, walletConnectMessage)
|
||||
|
||||
lnbitsUrl := Configuration.LnbitsPublicUrl
|
||||
if !strings.HasSuffix(lnbitsUrl, "/") {
|
||||
lnbitsUrl = lnbitsUrl + "/"
|
||||
}
|
||||
lndhubUrl := fmt.Sprintf("lndhub://admin:%s@%slndhub/ext/", fromUser.Wallet.Adminkey, lnbitsUrl)
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(lndhubUrl, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// send the invoice data to user
|
||||
bot.telegram.Send(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"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"
|
||||
)
|
||||
|
||||
const (
|
||||
lnurlReceiveInfoText = "👇 You can use this 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 via LNURL."
|
||||
lnurlEnterAmountMessage = "Please enter an amount."
|
||||
lnurlHelpText = "📖 Oops, that didn't work. %s\n\n" +
|
||||
"*Usage:* `/lnurl [amount] <lnurl>`\n" +
|
||||
"*Example:* `/lnurl LNURL1DP68GUR...`"
|
||||
)
|
||||
|
||||
// lnurlHandler is invoked on /lnurl command
|
||||
func (bot TipBot) lnurlHandler(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(m)
|
||||
return
|
||||
}
|
||||
|
||||
// assume payment
|
||||
// HandleLNURL by fiatjaf/go-lnurl
|
||||
msg, _ := bot.telegram.Send(m.Sender, lnurlResolvingUrlMessage)
|
||||
_, params, err := HandleLNURL(m.Text)
|
||||
if err != nil {
|
||||
bot.telegram.Edit(msg, fmt.Sprintf(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.telegram.Edit(msg, fmt.Sprintf(lnurlPaymentFailed, err))
|
||||
// bot.telegram.Send(m.Sender, err.Error())
|
||||
return
|
||||
}
|
||||
user, err := GetUser(m.Sender, bot)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.telegram.Edit(msg, fmt.Sprintf(lnurlPaymentFailed, "database error."))
|
||||
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
|
||||
}
|
||||
user.StateData = string(paramsJson)
|
||||
user.StateKey = lnbits.UserStateLNURLEnterAmount
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return
|
||||
}
|
||||
bot.telegram.Delete(msg)
|
||||
// Let the user enter an amount and return
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf(lnurlEnterAmountMessage), tb.ForceReply)
|
||||
} else {
|
||||
// amount is already present in the command
|
||||
// set also amount in the state of the user
|
||||
// todo: this is repeated code, could be shorter
|
||||
payParams.Amount = amount
|
||||
paramsJson, err := json.Marshal(payParams)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
// bot.telegram.Send(m.Sender, err.Error())
|
||||
return
|
||||
}
|
||||
user.StateData = string(paramsJson)
|
||||
user.StateKey = lnbits.UserStateConfirmLNURLPay
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
// bot.telegram.Send(m.Sender, err.Error())
|
||||
return
|
||||
}
|
||||
bot.telegram.Delete(msg)
|
||||
// directly go to confirm
|
||||
bot.lnurlPayHandler(m)
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) UserGetLightningAddress(user *tb.User) (string, error) {
|
||||
host, _, err := net.SplitHostPort(strings.Split(Configuration.LNURLServer, "//")[1])
|
||||
if err != nil {
|
||||
log.Errorf("[UserGetLightningAddress] Error: %s", err)
|
||||
return "", err
|
||||
}
|
||||
if len(user.Username) > 0 {
|
||||
return fmt.Sprintf("%s@%s", strings.ToLower(user.Username), strings.ToLower(host)), nil
|
||||
} else {
|
||||
return "", fmt.Errorf("user has no username.")
|
||||
}
|
||||
}
|
||||
|
||||
func (bot *TipBot) UserGetLNURL(user *tb.User) (string, error) {
|
||||
name := strings.ToLower(strings.ToLower(user.Username))
|
||||
if len(name) == 0 {
|
||||
return "", fmt.Errorf("user has no username.")
|
||||
}
|
||||
host, _, err := net.SplitHostPort(strings.Split(Configuration.LNURLServer, "//")[1])
|
||||
callback := fmt.Sprintf("https://%s/.well-known/lnurlp/%s", host, name)
|
||||
log.Infof("[lnurlReceiveHandler] %s's LNURL: %s", GetUserStr(user), callback)
|
||||
|
||||
lnurl, err := lnurl.LNURLEncode(callback)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return lnurl, nil
|
||||
}
|
||||
|
||||
// lnurlReceiveHandler outputs the LNURL of the user
|
||||
func (bot TipBot) lnurlReceiveHandler(m *tb.Message) {
|
||||
lnurl, err := bot.UserGetLNURL(m.Sender)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[lnurlReceiveHandler] Failed to get LNURL: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
bot.telegram.Send(m.Sender, lnurlNoUsernameMessage)
|
||||
}
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(lnurl, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[lnurlReceiveHandler] Failed to create QR code for LNURL: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
bot.telegram.Send(m.Sender, lnurlReceiveInfoText)
|
||||
// send the lnurl data to user
|
||||
bot.telegram.Send(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lnurl)})
|
||||
}
|
||||
|
||||
func (bot TipBot) lnurlEnterAmountHandler(m *tb.Message) {
|
||||
user, err := GetUser(m.Sender, bot)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
// bot.telegram.Send(m.Sender, err.Error())
|
||||
return
|
||||
}
|
||||
if user.StateKey == lnbits.UserStateLNURLEnterAmount {
|
||||
a, err := strconv.Atoi(m.Text)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.telegram.Send(m.Sender, lnurlInvalidAmountMessage)
|
||||
return
|
||||
}
|
||||
amount := int64(a)
|
||||
var stateResponse LnurlStateResponse
|
||||
err = json.Unmarshal([]byte(user.StateData), &stateResponse)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
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.telegram.Send(m.Sender, fmt.Sprintf(lnurlInvalidAmountRangeMessage, stateResponse.MinSendable/1000, stateResponse.MaxSendable/1000))
|
||||
return
|
||||
}
|
||||
stateResponse.Amount = a
|
||||
user.StateKey = lnbits.UserStateConfirmLNURLPay
|
||||
state, err := json.Marshal(stateResponse)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return
|
||||
}
|
||||
user.StateData = string(state)
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
return
|
||||
}
|
||||
bot.lnurlPayHandler(m)
|
||||
}
|
||||
}
|
||||
|
||||
// LnurlStateResponse saves the state of the user for an LNURL payment
|
||||
type LnurlStateResponse struct {
|
||||
lnurl.LNURLPayResponse1
|
||||
Amount int `json:"amount"`
|
||||
}
|
||||
|
||||
// lnurlPayHandler is invoked when the user has delivered an amount and is ready to pay
|
||||
func (bot TipBot) lnurlPayHandler(c *tb.Message) {
|
||||
msg, _ := bot.telegram.Send(c.Sender, lnurlGettingUserMessage)
|
||||
|
||||
user, err := GetUser(c.Sender, bot)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
// bot.telegram.Send(c.Sender, err.Error())
|
||||
bot.telegram.Edit(msg, fmt.Sprintf(lnurlPaymentFailed, "database error."))
|
||||
return
|
||||
}
|
||||
if user.StateKey == lnbits.UserStateConfirmLNURLPay {
|
||||
client, err := getHttpClient()
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
// bot.telegram.Send(c.Sender, err.Error())
|
||||
bot.telegram.Edit(msg, fmt.Sprintf(lnurlPaymentFailed, err))
|
||||
return
|
||||
}
|
||||
var stateResponse LnurlStateResponse
|
||||
err = json.Unmarshal([]byte(user.StateData), &stateResponse)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
// bot.telegram.Send(c.Sender, err.Error())
|
||||
bot.telegram.Edit(msg, fmt.Sprintf(lnurlPaymentFailed, err))
|
||||
return
|
||||
}
|
||||
callbackUrl, err := url.Parse(stateResponse.Callback)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
// bot.telegram.Send(c.Sender, err.Error())
|
||||
bot.telegram.Edit(msg, fmt.Sprintf(lnurlPaymentFailed, err))
|
||||
return
|
||||
}
|
||||
qs := callbackUrl.Query()
|
||||
qs.Set("amount", strconv.Itoa(stateResponse.Amount*1000))
|
||||
callbackUrl.RawQuery = qs.Encode()
|
||||
|
||||
res, err := client.Get(callbackUrl.String())
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
// bot.telegram.Send(c.Sender, err.Error())
|
||||
bot.telegram.Edit(msg, fmt.Sprintf(lnurlPaymentFailed, err))
|
||||
return
|
||||
}
|
||||
var response2 lnurl.LNURLPayResponse2
|
||||
body, err := ioutil.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
// bot.telegram.Send(c.Sender, err.Error())
|
||||
bot.telegram.Edit(msg, fmt.Sprintf(lnurlPaymentFailed, err))
|
||||
return
|
||||
}
|
||||
json.Unmarshal(body, &response2)
|
||||
|
||||
if len(response2.PR) < 1 {
|
||||
bot.telegram.Edit(msg, fmt.Sprintf(lnurlPaymentFailed, "could not receive invoice (wrong address?)."))
|
||||
return
|
||||
}
|
||||
bot.telegram.Delete(msg)
|
||||
c.Text = fmt.Sprintf("/pay %s", response2.PR)
|
||||
bot.confirmPaymentHandler(c)
|
||||
}
|
||||
}
|
||||
|
||||
func getHttpClient() (*http.Client, error) {
|
||||
client := http.Client{}
|
||||
if Configuration.HttpProxy != "" {
|
||||
proxyUrl, err := url.Parse(Configuration.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(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 {
|
||||
m.Text = fmt.Sprintf("/lnurl %d %s", amount, lnurl)
|
||||
} else {
|
||||
m.Text = fmt.Sprintf("/lnurl %s", lnurl)
|
||||
}
|
||||
bot.lnurlHandler(m)
|
||||
return nil
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"runtime/debug"
|
||||
)
|
||||
|
||||
// setLogger will initialize the log format
|
||||
@@ -24,5 +25,6 @@ func main() {
|
||||
func withRecovery() {
|
||||
if r := recover(); r != nil {
|
||||
log.Errorln("Recovered panic: ", r)
|
||||
debug.PrintStack()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,14 +13,14 @@ import (
|
||||
|
||||
const (
|
||||
paymentCancelledMessage = "🚫 Payment cancelled."
|
||||
invoicePaidMessage = "⚡️ Invoice paid."
|
||||
invoicePaidMessage = "⚡️ Payment sent."
|
||||
invoicePrivateChatOnlyErrorMessage = "You can pay invoices only in the private chat with the bot."
|
||||
invalidInvoiceHelpMessage = "Did you enter a valid Lightning invoice?"
|
||||
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 = "🚫 Failed to pay invoice: %s"
|
||||
confirmPayInvoiceMessage = "Do you want to pay this invoice?\n\n💸 Amount: %d sat"
|
||||
invoicePaymentFailedMessage = "🚫 Payment failed: %s"
|
||||
confirmPayInvoiceMessage = "Do you want to send this payment?\n\n💸 Amount: %d sat"
|
||||
confirmPayAppendMemo = "\n✉️ %s"
|
||||
payHelpText = "📖 Oops, that didn't work. %s\n\n" +
|
||||
"*Usage:* `/pay <invoice>`\n" +
|
||||
@@ -37,7 +37,8 @@ func helpPayInvoiceUsage(errormsg string) string {
|
||||
|
||||
// confirmPaymentHandler invoked on "/pay lnbc..." command
|
||||
func (bot TipBot) confirmPaymentHandler(m *tb.Message) {
|
||||
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package lightning
|
||||
|
||||
import (
|
||||
"net/mail"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -16,3 +17,8 @@ func IsInvoice(invoice string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func IsLightningAddress(address string) bool {
|
||||
_, err := mail.ParseAddress(address)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 107 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 55 KiB |
@@ -5,27 +5,28 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
sendValidAmountMessage = "Did you use a valid amount?"
|
||||
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."
|
||||
sendReceivedMessage = "🏅 %s 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 = "🚫 Sending cancelled."
|
||||
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 ❤️`"
|
||||
"*Example:* `/send 1000 @LightningTipBot I just like the bot ❤️`\n" +
|
||||
"*Example:* `/send 1234 LightningTipBot@ln.tips`"
|
||||
)
|
||||
|
||||
func helpSendUsage(errormsg string) string {
|
||||
@@ -36,37 +37,69 @@ func helpSendUsage(errormsg string) string {
|
||||
}
|
||||
}
|
||||
|
||||
func SendCheckSyntax(m *tb.Message) (bool, string) {
|
||||
func (bot *TipBot) 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 false, fmt.Sprintf("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.", bot.telegram.Me.Username)
|
||||
}
|
||||
// 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) {
|
||||
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
|
||||
// reset state immediately
|
||||
user, err := GetUser(m.Sender, *bot)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
user.ResetState()
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
|
||||
// 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))
|
||||
if ok, errstr := bot.SendCheckSyntax(m); !ok {
|
||||
bot.telegram.Send(m.Sender, helpSendUsage(errstr))
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
return
|
||||
}
|
||||
|
||||
// get send amount
|
||||
// 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) {
|
||||
// if the second argument is a lightning address, then send to that address
|
||||
err = bot.sendToLightningAddress(m, arg, amount)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// ASSUME INTERNAL SEND TO TELEGRAM USER
|
||||
if err != nil || amount < 1 {
|
||||
errmsg := fmt.Sprintf("[/send] Error: Send amount not valid.")
|
||||
log.Errorln(errmsg)
|
||||
@@ -77,7 +110,6 @@ func (bot *TipBot) confirmSendHandler(m *tb.Message) {
|
||||
}
|
||||
|
||||
// SEND COMMAND IS VALID
|
||||
|
||||
// check for memo in command
|
||||
sendMemo := ""
|
||||
if len(strings.Split(m.Text, " ")) > 3 {
|
||||
@@ -97,7 +129,7 @@ func (bot *TipBot) confirmSendHandler(m *tb.Message) {
|
||||
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)))
|
||||
bot.telegram.Send(m.Sender, helpSendUsage(fmt.Sprintf(sendUserNotFoundMessage, arg, bot.telegram.Me.Username)))
|
||||
log.Errorln(errmsg)
|
||||
|
||||
return
|
||||
@@ -112,7 +144,7 @@ func (bot *TipBot) confirmSendHandler(m *tb.Message) {
|
||||
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))
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf(sendIsNotAUsser, arg, bot.telegram.Me.Username))
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
@@ -120,8 +152,13 @@ func (bot *TipBot) confirmSendHandler(m *tb.Message) {
|
||||
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)
|
||||
tx := bot.database.Where("telegram_username = ?", strings.ToLower(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))
|
||||
@@ -137,16 +174,9 @@ func (bot *TipBot) confirmSendHandler(m *tb.Message) {
|
||||
sendData = sendData + "|" + sendMemo
|
||||
}
|
||||
|
||||
// old callback method
|
||||
// // this is the maximum length of what the callback supports
|
||||
// buttonMaxDataLength := 58
|
||||
// if len(btnSend.Data) > buttonMaxDataLength {
|
||||
// btnSend.Data = btnSend.Data[:buttonMaxDataLength]
|
||||
// }
|
||||
|
||||
// save the send data to the database
|
||||
log.Debug(sendData)
|
||||
user, err := GetUser(m.Sender, *bot)
|
||||
user, err = GetUser(m.Sender, *bot)
|
||||
if err != nil {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
log.Printf("[/send] Error: %s\n", err.Error())
|
||||
|
||||
@@ -14,26 +14,34 @@ import (
|
||||
|
||||
const (
|
||||
startSettingWalletMessage = "🧮 Setting up your wallet..."
|
||||
startWalletCreatedMessage = "🧮 Wallet created."
|
||||
startWalletReadyMessage = "✅ *Your wallet is ready.*"
|
||||
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."
|
||||
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."
|
||||
)
|
||||
|
||||
func (bot TipBot) startHandler(m *tb.Message) {
|
||||
if !m.Private() {
|
||||
return
|
||||
}
|
||||
bot.helpHandler(m)
|
||||
// ATTENTION: DO NOT CALL ANY HANDLER BEFORE THE WALLET IS CREATED
|
||||
// WILL RESULT IN AN ENDLESS LOOP OTHERWISE
|
||||
// bot.helpHandler(m)
|
||||
log.Printf("[/start] User: %s (%d)\n", m.Sender.Username, m.Sender.ID)
|
||||
|
||||
walletCreationMsg, err := bot.telegram.Send(m.Sender, startSettingWalletMessage)
|
||||
err = bot.initWallet(m.Sender)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[startHandler] Error with initWallet: %s", err.Error()))
|
||||
bot.telegram.Edit(walletCreationMsg, startWalletErrorMessage)
|
||||
return
|
||||
}
|
||||
bot.telegram.Edit(walletCreationMsg, startWalletReadyMessage)
|
||||
bot.telegram.Delete(walletCreationMsg)
|
||||
|
||||
bot.helpHandler(m)
|
||||
bot.telegram.Send(m.Sender, startWalletReadyMessage)
|
||||
bot.balanceHandler(m)
|
||||
|
||||
// send the user a warning about the fact that they need to set a username
|
||||
if len(m.Sender.Username) == 0 {
|
||||
bot.telegram.Send(m.Sender, startNoUsernameMessage, tb.NoPreview)
|
||||
}
|
||||
@@ -55,6 +63,7 @@ func (bot TipBot) initWallet(tguser *tb.User) error {
|
||||
return err
|
||||
}
|
||||
} else if !user.Initialized {
|
||||
// update all tip tooltips (with the "initialize me" message) that this user might have received before
|
||||
tipTooltipInitializedHandler(user.Telegram, bot)
|
||||
user.Initialized = true
|
||||
err = UpdateUserRecord(user, bot)
|
||||
@@ -62,6 +71,12 @@ func (bot TipBot) initWallet(tguser *tb.User) error {
|
||||
log.Errorln(fmt.Sprintf("[initWallet] error updating user: %s", err.Error()))
|
||||
return err
|
||||
}
|
||||
} else if user.Initialized {
|
||||
// wallet is already initialized
|
||||
return nil
|
||||
} else {
|
||||
err = fmt.Errorf("could not initialize wallet")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,22 +1,45 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
|
||||
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
|
||||
}
|
||||
// could be an invoice
|
||||
invoiceString := strings.ToLower(m.Text)
|
||||
if lightning.IsInvoice(invoiceString) {
|
||||
m.Text = "/pay " + invoiceString
|
||||
bot.confirmPaymentHandler(m)
|
||||
|
||||
// check if user is in database, if not, initialize wallet
|
||||
user, exists := bot.UserExists(m.Sender)
|
||||
if !exists {
|
||||
bot.startHandler(m)
|
||||
return
|
||||
}
|
||||
|
||||
// could be an invoice
|
||||
anyText := strings.ToLower(m.Text)
|
||||
if lightning.IsInvoice(anyText) {
|
||||
m.Text = "/pay " + anyText
|
||||
bot.confirmPaymentHandler(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(m)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -11,12 +11,13 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
tipDidYouReplyMessage = "Did you reply to a message to tip? To reply to a message, right-click -> Reply on your computer or swipe the message on your phone."
|
||||
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 use a valid amount?"
|
||||
tipValidAmountMessage = "Did you enter a valid amount?"
|
||||
tipYourselfMessage = "📖 You can't tip yourself."
|
||||
tipSentMessage = "💸 %d sat sent to %s."
|
||||
tipReceivedMessage = "🏅 You've received a %d sat tip from %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" +
|
||||
@@ -40,11 +41,13 @@ func TipCheckSyntax(m *tb.Message) (bool, string) {
|
||||
}
|
||||
|
||||
func (bot *TipBot) tipHandler(m *tb.Message) {
|
||||
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
|
||||
// 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)))
|
||||
bot.telegram.Send(m.Sender, tipInviteGroupMessage)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -65,6 +68,10 @@ func (bot *TipBot) tipHandler(m *tb.Message) {
|
||||
return
|
||||
}
|
||||
|
||||
err = bot.parseCmdDonHandler(m)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
// TIP COMMAND IS VALID
|
||||
|
||||
to := m.ReplyTo.Sender
|
||||
@@ -81,9 +88,9 @@ func (bot *TipBot) tipHandler(m *tb.Message) {
|
||||
toUserStr := GetUserStr(m.ReplyTo.Sender)
|
||||
fromUserStr := GetUserStr(from)
|
||||
|
||||
if !bot.UserHasWallet(to) {
|
||||
if _, exists := bot.UserExists(to); !exists {
|
||||
log.Infof("[/tip] User %s has no wallet.", toUserStr)
|
||||
err = bot.CreateWalletForUser(to)
|
||||
err = bot.CreateWalletForTelegramUser(to)
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[/tip] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
@@ -138,11 +145,10 @@ func (bot *TipBot) tipHandler(m *tb.Message) {
|
||||
if !messageHasTip {
|
||||
bot.telegram.Forward(to, m.ReplyTo, tb.Silent)
|
||||
}
|
||||
bot.telegram.Send(to, fmt.Sprintf(tipReceivedMessage, amount, fromUserStrMd))
|
||||
bot.telegram.Send(to, fmt.Sprintf(tipReceivedMessage, fromUserStrMd, amount))
|
||||
|
||||
if len(tipMemo) > 0 {
|
||||
bot.telegram.Send(to, fmt.Sprintf("✉️ %s", MarkdownEscape(tipMemo)))
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
@@ -94,13 +95,20 @@ func (bot *TipBot) GetUserBalance(user *tb.User) (amount int, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (bot *TipBot) CreateWalletForUser(tbUser *tb.User) error {
|
||||
user, err := GetUser(tbUser, *bot)
|
||||
func (bot *TipBot) copyLowercaseUser(u *tb.User) *tb.User {
|
||||
u_cp := *u
|
||||
u_cp.Username = strings.ToLower(u.Username)
|
||||
return &u_cp
|
||||
}
|
||||
|
||||
func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) error {
|
||||
u_cp := bot.copyLowercaseUser(tbUser)
|
||||
user := &lnbits.User{Telegram: u_cp}
|
||||
userStr := GetUserStr(tbUser)
|
||||
log.Printf("[CreateWalletForUser] Creating wallet for user %s ... ", userStr)
|
||||
err = bot.createWallet(user)
|
||||
log.Printf("[CreateWalletForTelegramUser] Creating wallet for user %s ... ", userStr)
|
||||
err := bot.createWallet(user)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[CreateWalletForUser] Error: Could not create wallet for user %s", userStr)
|
||||
errmsg := fmt.Sprintf("[CreateWalletForTelegramUser] Error: Could not create wallet for user %s", userStr)
|
||||
log.Errorln(errmsg)
|
||||
return err
|
||||
}
|
||||
@@ -108,14 +116,14 @@ func (bot *TipBot) CreateWalletForUser(tbUser *tb.User) error {
|
||||
if tx.Error != nil {
|
||||
return tx.Error
|
||||
}
|
||||
log.Printf("[CreateWalletForUser] Wallet created for user %s. ", userStr)
|
||||
log.Printf("[CreateWalletForTelegramUser] Wallet created for user %s. ", userStr)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (bot *TipBot) UserHasWallet(user *tb.User) bool {
|
||||
_, err := GetUser(user, *bot)
|
||||
func (bot *TipBot) UserExists(user *tb.User) (*lnbits.User, bool) {
|
||||
lnbitUser, err := GetUser(user, *bot)
|
||||
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return false
|
||||
return nil, false
|
||||
}
|
||||
return true
|
||||
return lnbitUser, true
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user