Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
998ed1db58 | ||
|
|
77c3a50c0c | ||
|
|
f3b3e3440b | ||
|
|
23785a650c | ||
|
|
d31e621720 | ||
|
|
cae8df6557 | ||
|
|
90ebd90d59 | ||
|
|
64c1bf1aa3 | ||
|
|
8d4b0a5f65 | ||
|
|
985952de00 | ||
|
|
3fe903bc51 | ||
|
|
4bf0e05d6c |
@@ -69,6 +69,7 @@ You can either use your own LNbits instance (recommended) or create an account a
|
||||
/pay ⚡️ Pay a Lightning invoice: /pay <invoice>
|
||||
/help 📖 Read this help.
|
||||
/info 📚 More info.
|
||||
/donate 🙏 Donate to @LightningTipBot: /donate <amount>
|
||||
```
|
||||
|
||||
### Live tooltips
|
||||
@@ -79,6 +80,14 @@ 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>
|
||||
|
||||
### 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.
|
||||
|
||||
+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,19 @@ 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,
|
||||
"/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 {
|
||||
@@ -123,5 +128,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()
|
||||
}
|
||||
|
||||
@@ -11,3 +11,5 @@ tip - Reply to a message to tip. Example: /tip 50
|
||||
send - Send funds to a Telegram user. Example: /send 100 @LightningTipBot
|
||||
invoice - Create a Lightning invoice to receive payments. Example: /invoice 1000
|
||||
pay - Pay a Lightning invoice. Example: /pay lnbc10n1ps...
|
||||
donate - Donate to the project: Example: /donate 1000
|
||||
advanced - Advanced help
|
||||
@@ -6,7 +6,9 @@ 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"`
|
||||
DbPath string `json:"db_path" yaml:"db_path"`
|
||||
TransactionsPath string `json:"transactions_path" yaml:"transactions_path"`
|
||||
|
||||
+4
-2
@@ -1,6 +1,8 @@
|
||||
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"
|
||||
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"
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
// PLEASE DO NOT CHANGE THE CODE IN THIS FILE
|
||||
// YOU MIGHT BREAK DONATIONS TO THE ORIGINAL PROJECT
|
||||
// THE DEVELOPMENT OF LIGHTNINGTIPBOT RELIES ON DONATIONS
|
||||
// IF YOU USE THIS PROJECT, LEAVE THIS CODE ALONE
|
||||
|
||||
var (
|
||||
donationSuccess = "🙏 Thank you for your donation."
|
||||
donationErrorMessage = "🚫 Oh no. Donation failed."
|
||||
donationFailedMessage = "🚫 Donation failed: %s"
|
||||
donateEnterAmountMessage = "Did you enter an amount?"
|
||||
donateValidAmountMessage = "Did you enter a valid amount?"
|
||||
donateHelpText = "📖 Oops, that didn't work. %s\n\n" +
|
||||
"*Usage:* `/donate <amount>`\n" +
|
||||
"*Example:* `/donate 1000`"
|
||||
endpoint string
|
||||
)
|
||||
|
||||
func helpDonateUsage(errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(donateHelpText, fmt.Sprintf("%s", errormsg))
|
||||
} else {
|
||||
return fmt.Sprintf(donateHelpText, "")
|
||||
}
|
||||
}
|
||||
|
||||
func (bot TipBot) donationHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
|
||||
if len(strings.Split(m.Text, " ")) < 2 {
|
||||
bot.telegram.Send(m.Sender, helpDonateUsage(donateEnterAmountMessage))
|
||||
return
|
||||
}
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if amount < 1 {
|
||||
bot.telegram.Send(m.Sender, helpDonateUsage(donateValidAmountMessage))
|
||||
return
|
||||
}
|
||||
|
||||
// command is valid
|
||||
|
||||
// get invoice
|
||||
resp, err := http.Get(fmt.Sprintf(endpoint, amount, GetUserStr(m.Sender), GetUserStr(bot.telegram.Me)))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.telegram.Send(m.Sender, donationErrorMessage)
|
||||
return
|
||||
}
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
bot.telegram.Send(m.Sender, donationErrorMessage)
|
||||
return
|
||||
}
|
||||
|
||||
// send donation invoice
|
||||
user, err := GetUser(m.Sender, bot)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// bot.telegram.Send(user.Telegram, string(body))
|
||||
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: string(body)}, *user.Wallet)
|
||||
if err != nil {
|
||||
userStr := GetUserStr(m.Sender)
|
||||
errmsg := fmt.Sprintf("[/donate] Donation failed for user %s: %s", userStr, err)
|
||||
log.Errorln(errmsg)
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf(donationFailedMessage, err))
|
||||
return
|
||||
}
|
||||
bot.telegram.Send(m.Sender, donationSuccess)
|
||||
|
||||
}
|
||||
|
||||
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("Vg ybbxf yvxr lbh'er znxvat n qbangvba. V'z ebhgvat guvf gb gur bevtvany cebwrpg.")})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
donationInterceptMessage := sb.String()
|
||||
|
||||
bot.telegram.Send(m.Sender, donationInterceptMessage)
|
||||
m.Text = fmt.Sprintf("/donate %d", amount)
|
||||
bot.donationHandler(m)
|
||||
// returning nil here will abort the parent handler (/pay or /tip)
|
||||
return nil
|
||||
}
|
||||
@@ -3,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
|
||||
|
||||
@@ -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,22 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
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 it with 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" +
|
||||
"⚙️ *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" +
|
||||
"*/help* 📖 Read this help.\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" +
|
||||
@@ -32,11 +33,15 @@ const (
|
||||
// "🏛 *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 it with 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`"
|
||||
|
||||
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) {
|
||||
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)
|
||||
@@ -46,7 +51,8 @@ func (bot TipBot) helpHandler(m *tb.Message) {
|
||||
}
|
||||
|
||||
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)
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
if !m.Private() {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
@@ -54,3 +60,14 @@ func (bot TipBot) infoHandler(m *tb.Message) {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -34,10 +34,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 {
|
||||
|
||||
@@ -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,208 @@
|
||||
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 = 100000000
|
||||
)
|
||||
|
||||
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,
|
||||
CommentAllowed: 512,
|
||||
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 = ?", 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)
|
||||
}
|
||||
+2
-13
@@ -28,20 +28,9 @@ func helpInvoiceUsage(errormsg string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// func helpInvoiceUsage(errormsg string) string {
|
||||
// helpstr := "📖 Oops, that didn't work. %s\n\n" +
|
||||
// "*Usage:* `/invoice <amount> [<memo>]`\n" +
|
||||
// "*Example:* `/invoice 1000 Take this! 💸`"
|
||||
// if len(errormsg) > 0 {
|
||||
// helpstr = fmt.Sprintf(helpstr, fmt.Sprintf("%s", errormsg))
|
||||
// } else {
|
||||
// helpstr = fmt.Sprintf(helpstr, "")
|
||||
// }
|
||||
// return helpstr
|
||||
// }
|
||||
|
||||
func (bot TipBot) invoiceHandler(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)
|
||||
|
||||
@@ -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)})
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 107 KiB |
@@ -52,7 +52,8 @@ func SendCheckSyntax(m *tb.Message) (bool, string) {
|
||||
|
||||
// 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)
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
// If the send is a reply, then trigger /tip handler
|
||||
if m.IsReply() {
|
||||
bot.tipHandler(m)
|
||||
@@ -120,6 +121,11 @@ 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)
|
||||
if tx.Error != nil || toUserDb.Wallet == nil || toUserDb.Initialized == false {
|
||||
@@ -137,13 +143,6 @@ 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)
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
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."
|
||||
)
|
||||
|
||||
@@ -22,18 +23,22 @@ 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)
|
||||
bot.telegram.Send(m.Sender, helpMessage, tb.NoPreview)
|
||||
log.Printf("[/start] User: %s (%d)\n", m.Sender.Username, m.Sender.ID)
|
||||
|
||||
walletCreationMsg, err := bot.telegram.Send(m.Sender, startSettingWalletMessage)
|
||||
err = bot.initWallet(m.Sender)
|
||||
if err != nil {
|
||||
log.Errorln(fmt.Sprintf("[startHandler] Error with initWallet: %s", err.Error()))
|
||||
bot.telegram.Edit(walletCreationMsg, startWalletErrorMessage)
|
||||
return
|
||||
}
|
||||
bot.telegram.Edit(walletCreationMsg, startWalletReadyMessage)
|
||||
bot.balanceHandler(m)
|
||||
|
||||
// send the user a warning about the fact that they need to set a username
|
||||
if len(m.Sender.Username) == 0 {
|
||||
bot.telegram.Send(m.Sender, startNoUsernameMessage, tb.NoPreview)
|
||||
}
|
||||
@@ -63,6 +68,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
|
||||
}
|
||||
|
||||
@@ -9,15 +9,20 @@ import (
|
||||
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) {
|
||||
log.Infof("User %s has no wallet, force-initializing", GetUserStr(m.Sender))
|
||||
bot.startHandler(m)
|
||||
return
|
||||
}
|
||||
|
||||
// could be an invoice
|
||||
@@ -25,5 +30,6 @@ func (bot TipBot) anyTextHandler(m *tb.Message) {
|
||||
if lightning.IsInvoice(invoiceString) {
|
||||
m.Text = "/pay " + invoiceString
|
||||
bot.confirmPaymentHandler(m)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +40,8 @@ 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)
|
||||
@@ -65,6 +66,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
|
||||
|
||||
Reference in New Issue
Block a user