Compare commits

...
6 Commits
Author SHA1 Message Date
LightningTipBotandGitHub 90ebd90d59 und 2021-08-27 20:39:21 +02:00
LightningTipBotandGitHub 64c1bf1aa3 fix public url for lndhub (#25) 2021-08-27 13:28:39 +02:00
LightningTipBotandGitHub 8d4b0a5f65 Lndhub (#24)
* lndhub support
* update readme
2021-08-27 13:17:44 +02:00
gohumbleandGitHub 985952de00 donations 2021-08-27 10:09:57 +02:00
LightningTipBotandGitHub 3fe903bc51 Force start2 (#21)
* force-init only on / commands

* return statemet

* anytext handler in all commands

* comment

* warning

* get rid of init bot wallet error
2021-08-25 02:13:42 +02:00
LightningTipBotandGitHub 4bf0e05d6c force-init only on / commands (#20)
* force-init only on / commands

* return statemet
2021-08-25 01:24:31 +02:00
16 changed files with 302 additions and 44 deletions
+9
View File
@@ -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.
<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
View File
@@ -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
+13 -10
View File
@@ -76,16 +76,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 {
+2
View File
@@ -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
+1
View File
@@ -6,6 +6,7 @@ var Configuration = struct {
AdminKey string `json:"lnbits_admin_id" yaml:"lnbits_admin_id"`
LnbitsKey string `json:"lnbits_admin_key" yaml:"lnbits_admin_key"`
LnbitsUrl string `json:"lnbits_url" yaml:"lnbits_url"`
LnbitsPublicUrl string `json:"lnbits_public_url" yaml:"lnbits_public_url"`
WebhookServer string `json:"webhook_server" yaml:"webhook_server"`
ApiKey string `json:"telegram_api_key" yaml:"telegram_api_key"`
DbPath string `json:"db_path" yaml:"db_path"`
+2 -1
View File
@@ -1,6 +1,7 @@
telegram_api_key: "1234"
webhook_server: "http://0.0.0.0:1234"
lnbits_url: "http://*.onion:1234"
lnbits_url: "http://127.0.0.1:1234"
lnbits_public_url: "http://*.onion:1234"
lnbits_admin_key: "1234"
lnbits_admin_id: "3212"
db_path: "data/bot.db"
+161
View File
@@ -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 init() {
var sb strings.Builder
_, err := io.Copy(&sb, rot13Reader{strings.NewReader("uggcf://ya.gvcf/qbangr/%q?sebz=%f&obg=%f")})
if err != nil {
panic(err)
}
endpoint = sb.String()
}
func helpDonateUsage(errormsg string) string {
if len(errormsg) > 0 {
return fmt.Sprintf(donateHelpText, fmt.Sprintf("%s", errormsg))
} else {
return fmt.Sprintf(donateHelpText, "")
}
}
func (bot TipBot) donationHandler(m *tb.Message) {
// check and print all commands
bot.anyTextHandler(m)
if len(strings.Split(m.Text, " ")) < 2 {
bot.telegram.Send(m.Sender, helpDonateUsage(donateEnterAmountMessage))
return
}
amount, err := decodeAmountFromCommand(m.Text)
if err != nil {
return
}
if amount < 1 {
bot.telegram.Send(m.Sender, helpDonateUsage(donateValidAmountMessage))
return
}
// command is valid
// get invoice
resp, err := http.Get(fmt.Sprintf(endpoint, amount, GetUserStr(m.Sender), GetUserStr(bot.telegram.Me)))
if err != nil {
log.Errorln(err)
bot.telegram.Send(m.Sender, donationErrorMessage)
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorln(err)
bot.telegram.Send(m.Sender, donationErrorMessage)
return
}
// send donation invoice
user, err := GetUser(m.Sender, bot)
if err != nil {
return
}
// bot.telegram.Send(user.Telegram, string(body))
_, err = user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: string(body)}, *user.Wallet)
if err != nil {
userStr := GetUserStr(m.Sender)
errmsg := fmt.Sprintf("[/donate] Donation failed for user %s: %s", userStr, err)
log.Errorln(errmsg)
bot.telegram.Send(m.Sender, fmt.Sprintf(donationFailedMessage, err))
return
}
bot.telegram.Send(m.Sender, donationSuccess)
}
type rot13Reader struct {
r io.Reader
}
func (rot13 rot13Reader) Read(b []byte) (int, error) {
n, err := rot13.r.Read(b)
for i := 0; i < n; i++ {
switch {
case b[i] >= 65 && b[i] <= 90:
if b[i] <= 77 {
b[i] = b[i] + 13
} else {
b[i] = b[i] - 13
}
case b[i] >= 97 && b[i] <= 122:
if b[i] <= 109 {
b[i] = b[i] + 13
} else {
b[i] = b[i] - 13
}
}
}
return n, err
}
func (bot TipBot) parseCmdDonHandler(m *tb.Message) error {
arg := ""
if strings.HasPrefix(strings.ToLower(m.Text), "/send") {
arg, _ = getArgumentFromCommand(m.Text, 2)
if arg != "@"+bot.telegram.Me.Username {
return fmt.Errorf("err")
}
}
if strings.HasPrefix(strings.ToLower(m.Text), "/tip") {
arg = GetUserStr(m.ReplyTo.Sender)
if arg != "@"+bot.telegram.Me.Username {
return fmt.Errorf("err")
}
}
if arg == "@LightningTipBot" || len(arg) < 1 {
return fmt.Errorf("err")
}
amount, err := decodeAmountFromCommand(m.Text)
if err != nil {
return err
}
var sb strings.Builder
_, err = io.Copy(&sb, rot13Reader{strings.NewReader("Vg ybbxf yvxr lbh'er znxvat n qbangvba. V'z ebhgvat guvf gb gur bevtvany cebwrpg.")})
if err != nil {
panic(err)
}
donationInterceptMessage := sb.String()
bot.telegram.Send(m.Sender, donationInterceptMessage)
m.Text = fmt.Sprintf("/donate %d", amount)
bot.donationHandler(m)
// returning nil here will abort the parent handler (/pay or /tip)
return nil
}
+23 -6
View File
@@ -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, 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
}
+2 -13
View File
@@ -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)
+52
View File
@@ -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 -1
View File
@@ -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: 172 KiB

+7 -8
View File
@@ -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)
+13 -2
View File
@@ -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
}
+7 -1
View File
@@ -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
}
}
+6 -1
View File
@@ -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