Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b6b73e8727 | ||
|
|
da82835e63 | ||
|
|
5deb5d940e | ||
|
|
8b4c5e2db0 | ||
|
|
6f5bfd2e87 | ||
|
|
15601d1477 | ||
|
|
1b207f5ddf | ||
|
|
357124b1b1 | ||
|
|
e77045e673 | ||
|
|
d376c82c74 | ||
|
|
5d8f66e33f | ||
|
|
3212e573b9 | ||
|
|
7b3da1f110 | ||
|
|
83a61968f6 | ||
|
|
f21bce2b1f | ||
|
|
3e74e98802 |
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 neurolib-dev
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,17 +1,16 @@
|
||||
<p align="center">
|
||||
<img alt="logo" src="resources/logo_round.png" >
|
||||
</p>
|
||||
</p>
|
||||
|
||||
|
||||
# @LightningTipBot 🏅
|
||||
|
||||
A Telegram Lightning ⚡️ Bitcoin wallet and tip bot for group chats.
|
||||
A tip bot for Telegram group chats that can send and receive Bitcoin via the Lightning Network ⚡️.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## Setting up the bot
|
||||
|
||||
### Installation
|
||||
|
||||
To build the bot from source, clone the repository and compile the source code.
|
||||
|
||||
```
|
||||
@@ -21,7 +20,9 @@ go build .
|
||||
cp config.yaml-example config.yaml
|
||||
```
|
||||
|
||||
After the configuration (see below), start it using the command
|
||||
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
|
||||
|
||||
```
|
||||
./LightningTipBot
|
||||
@@ -33,9 +34,9 @@ You need to edit `config.yaml` before starting the bot.
|
||||
|
||||
#### Create a Telegram bot
|
||||
|
||||
First, create a new Telegram bot by starting a conversation with the [@BotFather](https://core.telegram.org/bots#6-botfather). After you have created your bot, you will get an **Api Token** which you need to add to `telegram_api_key` in config.yaml accordingly.
|
||||
First, create a new Telegram bot by starting a conversation with the [@BotFather](https://core.telegram.org/bots#6-botfather). After you have created your bot, you will get an **Api Token** which you need to add to `telegram_api_key` in config.yaml accordingly.
|
||||
|
||||
#### Set up LNbits
|
||||
#### Set up LNbits
|
||||
|
||||
You can either use your own LNbits instance (recommended) or create an account at [lnbits.com](https://lnbits.com/) to use their custodial service (easy).
|
||||
|
||||
@@ -48,19 +49,17 @@ You can either use your own LNbits instance (recommended) or create an account a
|
||||
|
||||
<p align="center">
|
||||
<img alt="How to set up a lnbits wallet and the User Manager extension." src="resources/lnbits_setup.png" >
|
||||
</p>
|
||||
</p>
|
||||
|
||||
#### 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).
|
||||
* `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).
|
||||
|
||||
## Features
|
||||
|
||||
### Commands
|
||||
|
||||
```
|
||||
/tip 🏅 Reply to a message to tip it: /tip <amount> [<memo>]
|
||||
/balance 👑 Check your balance: /balance
|
||||
@@ -68,8 +67,6 @@ You can either use your own LNbits instance (recommended) or create an account a
|
||||
/invoice ⚡️ Create a Lightning invoice to receive payments: /invoice <amount> [<memo>]
|
||||
/pay ⚡️ Pay a Lightning invoice: /pay <invoice>
|
||||
/help 📖 Read this help.
|
||||
/info 📚 More info.
|
||||
/donate 🙏 Donate to @LightningTipBot: /donate <amount>
|
||||
```
|
||||
|
||||
### Live tooltips
|
||||
@@ -78,31 +75,16 @@ The bot replies to a tipped message to indicate to all participants how many and
|
||||
|
||||
<p align="center">
|
||||
<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.
|
||||
|
||||
<p align="center">
|
||||
<img alt="QR code payment example." src="resources/qr_code_example.jpg" >
|
||||
</p>
|
||||
</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.
|
||||
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.
|
||||
|
||||
## Made with
|
||||
* [LNbits](https://github.com/lnbits/lnbits) – Free and open-source lightning-network wallet/accounts system.
|
||||
* [telebot](https://github.com/tucnak/telebot) – A Telegram bot framework in Go.
|
||||
* [lnpay-go](https://github.com/lnpay/lnpay-go) – A library that talks to the LNPay.co Golang API.
|
||||
* [go-qrcode](https://github.com/skip2/go-qrcode) – QR Code encoder in Go.
|
||||
* [ln-decodepay](https://github.com/fiatjaf/ln-decodepay) – Lightning Network BOLT11 invoice decoder.
|
||||
|
||||
- [LNbits](https://github.com/lnbits/lnbits) – Free and open-source lightning-network wallet/accounts system.
|
||||
- [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.
|
||||
|
||||
+4
-2
@@ -8,13 +8,15 @@ import (
|
||||
|
||||
func getArgumentFromCommand(input string, which int) (output string, err error) {
|
||||
if len(strings.Split(input, " ")) < which+1 {
|
||||
return "", errors.New("Message doesn't contain enough arguments")
|
||||
errmsg := "Message doesn't contain enoough arguments"
|
||||
// log.Errorln(errmsg)
|
||||
return "None", errors.New(errmsg)
|
||||
}
|
||||
output = strings.Split(input, " ")[which]
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func decodeAmountFromCommand(input string) (amount int, err error) {
|
||||
func DecodeAmountFromCommand(input string) (amount int, err error) {
|
||||
if len(strings.Split(input, " ")) < 2 {
|
||||
errmsg := "Message doesn't contain any amount"
|
||||
// log.Errorln(errmsg)
|
||||
|
||||
+3
-7
@@ -9,25 +9,21 @@ import (
|
||||
)
|
||||
|
||||
func (bot TipBot) balanceHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
// reply only in private message
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
}
|
||||
// first check whether the user is initialized
|
||||
// first check if the user is initialized
|
||||
// note: this is another GetUser call that could be avoided
|
||||
fromUser, err := GetUser(m.Sender, bot)
|
||||
if err != nil {
|
||||
log.Errorf("[/balance] Error: %s", err)
|
||||
return
|
||||
}
|
||||
if !fromUser.Initialized {
|
||||
bot.startHandler(m)
|
||||
return
|
||||
}
|
||||
|
||||
usrStr := GetUserStr(m.Sender)
|
||||
// log.Infof("[/balance] Getting %s's balance", usrStr)
|
||||
balance, err := bot.GetUserBalance(m.Sender)
|
||||
if err != nil {
|
||||
log.Errorf("[/balance] Error fetching %s's balance: %s", usrStr, err)
|
||||
|
||||
@@ -24,15 +24,9 @@ type TipBot struct {
|
||||
}
|
||||
|
||||
var (
|
||||
paymentConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelPay = paymentConfirmationMenu.Data("🚫 Cancel", "cancel_pay")
|
||||
btnPay = paymentConfirmationMenu.Data("✅ Pay", "confirm_pay")
|
||||
sendConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
btnCancelSend = sendConfirmationMenu.Data("🚫 Cancel", "cancel_send")
|
||||
btnSend = sendConfirmationMenu.Data("✅ Send", "confirm_send")
|
||||
|
||||
botWalletInitialisation = sync.Once{}
|
||||
telegramHandlerRegistration = sync.Once{}
|
||||
paymentConfirmationMenu = &tb.ReplyMarkup{ResizeReplyKeyboard: true, OneTimeKeyboard: true}
|
||||
btnCancel = paymentConfirmationMenu.Data("🚫 Cancel", "cancel")
|
||||
btnPay = paymentConfirmationMenu.Data("✅ Pay", "pay")
|
||||
)
|
||||
|
||||
// NewBot migrates data and creates a new bot
|
||||
@@ -45,6 +39,34 @@ func NewBot() TipBot {
|
||||
}
|
||||
}
|
||||
|
||||
// Start will initialize the all social media bots and lnbits.
|
||||
func (bot TipBot) Start() {
|
||||
// set logger
|
||||
setLogger()
|
||||
// set up lnbits api
|
||||
bot.client = lnbits.NewClient(Configuration.LnbitsKey, Configuration.LnbitsUrl)
|
||||
// set up telebot
|
||||
bot.telegram = newTelegramBot()
|
||||
log.Infof("[Telegram] Authorized on account @%s", bot.telegram.Me.Username)
|
||||
// initialize the bot wallet
|
||||
err := bot.initBotWallet()
|
||||
if err != nil {
|
||||
log.Errorf("Could not initialize bot wallet: %s", err.Error())
|
||||
}
|
||||
bot.registerTelegramHandlers()
|
||||
lnbits.NewWebhook(Configuration.WebhookServer, bot.telegram, bot.client, bot.database)
|
||||
bot.telegram.Start()
|
||||
}
|
||||
|
||||
// setLogger will initialize the log format
|
||||
func setLogger() {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
customFormatter := new(log.TextFormatter)
|
||||
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
|
||||
customFormatter.FullTimestamp = true
|
||||
log.SetFormatter(customFormatter)
|
||||
}
|
||||
|
||||
// newTelegramBot will create a new telegram bot.
|
||||
func newTelegramBot() *tb.Bot {
|
||||
tgb, err := tb.NewBot(tb.Settings{
|
||||
@@ -58,6 +80,8 @@ func newTelegramBot() *tb.Bot {
|
||||
return tgb
|
||||
}
|
||||
|
||||
var botWalletInitialisation = sync.Once{}
|
||||
|
||||
// initBotWallet will create / initialize the bot wallet
|
||||
// todo -- may want to derive user wallets from this specific bot wallet (master wallet), since lnbits usermanager extension is able to do that.
|
||||
func (bot TipBot) initBotWallet() error {
|
||||
@@ -71,60 +95,83 @@ func (bot TipBot) initBotWallet() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
var telegramHandlerRegistration = sync.Once{}
|
||||
|
||||
// registerTelegramHandlers will register all telegram handlers.
|
||||
func (bot TipBot) registerTelegramHandlers() {
|
||||
telegramHandlerRegistration.Do(func() {
|
||||
// Set up handlers
|
||||
var endpointHandler = map[string]interface{}{
|
||||
"/tip": bot.tipHandler,
|
||||
"/pay": bot.confirmPaymentHandler,
|
||||
"/invoice": bot.invoiceHandler,
|
||||
"/balance": bot.balanceHandler,
|
||||
"/start": bot.startHandler,
|
||||
"/send": bot.confirmSendHandler,
|
||||
"/help": bot.helpHandler,
|
||||
"/info": bot.infoHandler,
|
||||
"/donate": bot.donationHandler,
|
||||
"/advanced": bot.advancedHelpHandler,
|
||||
"/link": bot.lndhubHandler,
|
||||
tb.OnPhoto: bot.privatePhotoHandler,
|
||||
tb.OnText: bot.anyTextHandler,
|
||||
"/tip": bot.tipHandler,
|
||||
"/pay": bot.confirmPaymentHandler,
|
||||
"/invoice": bot.invoiceHandler,
|
||||
"/balance": bot.balanceHandler,
|
||||
"/start": bot.startHandler,
|
||||
"/send": bot.sendHandler,
|
||||
"/help": bot.helpHandler,
|
||||
"/info": bot.infoHandler,
|
||||
}
|
||||
// assign handler to endpoint
|
||||
for endpoint, handler := range endpointHandler {
|
||||
log.Debugf("Registering: %s", endpoint)
|
||||
bot.telegram.Handle(endpoint, handler)
|
||||
|
||||
// if the endpoint is a string command (not photo etc)
|
||||
if strings.HasPrefix(endpoint, "/") {
|
||||
// register upper case versions as well
|
||||
bot.telegram.Handle(strings.ToUpper(endpoint), handler)
|
||||
}
|
||||
// register upper case versions as well
|
||||
bot.telegram.Handle(strings.ToUpper(endpoint), handler)
|
||||
}
|
||||
|
||||
// button handlers
|
||||
// for /pay
|
||||
bot.telegram.Handle(&btnPay, bot.payHandler)
|
||||
bot.telegram.Handle(&btnCancelPay, bot.cancelPaymentHandler)
|
||||
// for /send
|
||||
bot.telegram.Handle(&btnSend, bot.sendHandler)
|
||||
bot.telegram.Handle(&btnCancelSend, bot.cancelSendHandler)
|
||||
bot.telegram.Handle(&btnCancel, bot.cancelPaymentHandler)
|
||||
|
||||
// basic handlers
|
||||
bot.telegram.Handle(tb.OnText, func(m *tb.Message) {
|
||||
userStr := GetUserStr(m.Sender)
|
||||
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, userStr, m.Sender.ID, m.Text)
|
||||
bot.anyTextHandler(m)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Start will initialize the telegram bot and lnbits.
|
||||
func (bot TipBot) Start() {
|
||||
// set up lnbits api
|
||||
bot.client = lnbits.NewClient(Configuration.LnbitsKey, Configuration.LnbitsUrl)
|
||||
// set up telebot
|
||||
bot.telegram = newTelegramBot()
|
||||
log.Infof("[Telegram] Authorized on account @%s", bot.telegram.Me.Username)
|
||||
// initialize the bot wallet
|
||||
err := bot.initBotWallet()
|
||||
if err != nil {
|
||||
log.Errorf("Could not initialize bot wallet: %s", err.Error())
|
||||
func (bot TipBot) anyTextHandler(m *tb.Message) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return
|
||||
}
|
||||
// could be an invoice
|
||||
invoice_str := strings.ToLower(m.Text)
|
||||
if strings.HasPrefix(invoice_str, "lnbc") || strings.HasPrefix(invoice_str, "lightning:lnbc") {
|
||||
// if it's only one word
|
||||
if !strings.Contains(invoice_str, " ") {
|
||||
m.Text = "/pay " + invoice_str
|
||||
bot.confirmPaymentHandler(m)
|
||||
}
|
||||
}
|
||||
bot.registerTelegramHandlers()
|
||||
lnbits.NewWebhook(Configuration.WebhookServer, bot.telegram, bot.client, bot.database)
|
||||
bot.telegram.Start()
|
||||
}
|
||||
|
||||
func removeTip(tips []*Message, s int) []*Message {
|
||||
if len(tips) == 1 {
|
||||
return make([]*Message, 0)
|
||||
}
|
||||
return append(tips[:s], tips[s+1:]...)
|
||||
}
|
||||
|
||||
func (bot *TipBot) cleanupTipsFromMemory() {
|
||||
go func() {
|
||||
defer withRecovery()
|
||||
for {
|
||||
for userId, userTips := range bot.tips {
|
||||
for i, tip := range userTips {
|
||||
if time.Now().Sub(tip.LastTip) > (time.Hour*24)*7 {
|
||||
userTips = removeTip(userTips, i)
|
||||
err := bot.telegram.Delete(tip.Message)
|
||||
if err != nil {
|
||||
log.WithField("error", err.Error()).Error("could not delete tip tool tip")
|
||||
}
|
||||
bot.tips[userId] = userTips
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
time.Sleep(time.Hour)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -7,9 +7,7 @@
|
||||
|
||||
help - Read the help.
|
||||
balance - Check your balance.
|
||||
tip - Reply to a message to tip. Example: /tip 50
|
||||
send - Send funds to a Telegram user. Example: /send 100 @LightningTipBot
|
||||
invoice - Create a Lightning invoice to receive payments. Example: /invoice 1000
|
||||
pay - Pay a Lightning invoice. Example: /pay lnbc10n1ps...
|
||||
donate - Donate to the project: Example: /donate 1000
|
||||
advanced - Advanced help
|
||||
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.
|
||||
|
||||
@@ -6,7 +6,6 @@ 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"`
|
||||
|
||||
+1
-2
@@ -1,7 +1,6 @@
|
||||
telegram_api_key: "1234"
|
||||
webhook_server: "http://0.0.0.0:1234"
|
||||
lnbits_url: "http://127.0.0.1:1234"
|
||||
lnbits_public_url: "http://*.onion:1234"
|
||||
lnbits_url: "http://*.onion:1234"
|
||||
lnbits_admin_key: "1234"
|
||||
lnbits_admin_id: "3212"
|
||||
db_path: "data/bot.db"
|
||||
|
||||
+11
-20
@@ -2,7 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -15,13 +14,15 @@ import (
|
||||
|
||||
func migration() (db *gorm.DB, txLogger *gorm.DB) {
|
||||
txLogger, err := gorm.Open(sqlite.Open(Configuration.TransactionsPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
|
||||
if err != nil {
|
||||
panic("Initialize orm failed.")
|
||||
panic("initialize orm failed")
|
||||
}
|
||||
|
||||
orm, err := gorm.Open(sqlite.Open(Configuration.DbPath), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true, FullSaveAssociations: true})
|
||||
|
||||
if err != nil {
|
||||
panic("Initialize orm failed.")
|
||||
panic("initialize orm failed")
|
||||
}
|
||||
|
||||
err = orm.AutoMigrate(&lnbits.User{})
|
||||
@@ -35,30 +36,20 @@ func migration() (db *gorm.DB, txLogger *gorm.DB) {
|
||||
return orm, txLogger
|
||||
}
|
||||
|
||||
// GetUser from telegram user. Update the user if user information changed.
|
||||
// GetUser from telegram user
|
||||
func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
|
||||
user := &lnbits.User{Name: strconv.Itoa(u.ID)}
|
||||
tx := bot.database.First(user)
|
||||
user.Telegram = u
|
||||
if tx.Error != nil {
|
||||
errmsg := fmt.Sprintf("[GetUser] Couldn't fetch %s's info from database.", GetUserStr(u))
|
||||
log.Warnln(errmsg)
|
||||
return user, tx.Error
|
||||
}
|
||||
defer func() {
|
||||
user.Wallet.Client = bot.client
|
||||
}()
|
||||
var err error
|
||||
go func() {
|
||||
if !reflect.DeepEqual(u, user.Telegram) {
|
||||
// update possibly changed user details in database
|
||||
user.Telegram = u
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
log.Warnln(fmt.Sprintf("[UpdateUserRecord] %s", err.Error()))
|
||||
}
|
||||
}
|
||||
}()
|
||||
return user, err
|
||||
user.Wallet.Client = bot.client
|
||||
|
||||
// update possibly changed user details in database
|
||||
return user, UpdateUserRecord(user, bot)
|
||||
}
|
||||
|
||||
func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
|
||||
@@ -68,6 +59,6 @@ func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
|
||||
log.Errorln(errmsg)
|
||||
return tx.Error
|
||||
}
|
||||
log.Debugf("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
|
||||
// log.Infof("[UpdateUserRecord] Records of user %s updated.", GetUserStr(user.Telegram))
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package main
|
||||
|
||||
// func deleteMessage(update tgbotapi.Update, bot TipBot) error {
|
||||
// TippedMessage(update.Message, time.Millisecond*time.Duration(0)).Dispose(bot.telegram)
|
||||
// // m.Dispose(bot.telegram)
|
||||
// return nil
|
||||
// }
|
||||
@@ -1,161 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -8,7 +8,6 @@ require (
|
||||
github.com/imroc/req v0.3.0
|
||||
github.com/jinzhu/configor v1.2.1
|
||||
github.com/liyue201/goqr v0.0.0-20200803022322-df443203d4ea
|
||||
github.com/makiuchi-d/gozxing v0.0.2
|
||||
github.com/sirupsen/logrus v1.2.0
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||
gopkg.in/tucnak/telebot.v2 v2.3.5
|
||||
|
||||
@@ -150,8 +150,6 @@ github.com/liyue201/goqr v0.0.0-20200803022322-df443203d4ea/go.mod h1:w4pGU9PkiX
|
||||
github.com/ltcsuite/ltcd v0.0.0-20190101042124-f37f8bf35796 h1:sjOGyegMIhvgfq5oaue6Td+hxZuf3tDC8lAPrFldqFw=
|
||||
github.com/ltcsuite/ltcd v0.0.0-20190101042124-f37f8bf35796/go.mod h1:3p7ZTf9V1sNPI5H8P3NkTFF4LuwMdPl2DodF60qAKqY=
|
||||
github.com/ltcsuite/ltcutil v0.0.0-20181217130922-17f3b04680b6/go.mod h1:8Vg/LTOO0KYa/vlHWJ6XZAevPQThGH5sufO0Hrou/lA=
|
||||
github.com/makiuchi-d/gozxing v0.0.2 h1:TGSCQRXd9QL1ze1G1JE9sZBMEr6/HLx7m5ADlLUgq7E=
|
||||
github.com/makiuchi-d/gozxing v0.0.2/go.mod h1:Tt5nF+kNliU+5MDxqPpsFrtsWNdABQho/xdCZZVKCQc=
|
||||
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
|
||||
github.com/mattn/go-sqlite3 v1.14.5 h1:1IdxlwTNazvbKJQSxoJ5/9ECbEeaTTyeU7sEAZ5KKTQ=
|
||||
github.com/mattn/go-sqlite3 v1.14.5/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
|
||||
@@ -243,14 +241,9 @@ golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2 h1:z99zHgr7hKfrUcX/KsoJk5FJfjTceCKIp96+biqP4To=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ=
|
||||
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||
google.golang.org/genproto v0.0.0-20190201180003-4b09977fb922/go.mod h1:L3J43x8/uS+qIUoksaLKe6OS3nUKxOKuIFz1sl2/jx4=
|
||||
|
||||
@@ -5,18 +5,16 @@ import (
|
||||
)
|
||||
|
||||
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" +
|
||||
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" +
|
||||
"❤️ *Donate*\n" +
|
||||
"_This bot charges no fees but costs satoshis to operate. If you like the bot, please consider supporting this project with a donation. To donate, use_ `/donate 1000`\n\n" +
|
||||
"_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" +
|
||||
"⚙️ *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" +
|
||||
"*/tip* 🏅 Reply to a message to tip it: `/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" +
|
||||
"*/donate* ❤️ Donate to the project: `/donate 1000`\n" +
|
||||
"*/advanced* 🤖 Read the advanced help.\n" +
|
||||
"*/help* 📖 Read this help."
|
||||
"*/help* 📖 Read this help (more: */info*).\n"
|
||||
|
||||
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" +
|
||||
@@ -25,23 +23,14 @@ 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. 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" +
|
||||
"_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" +
|
||||
"📄 *Open Source*\n" +
|
||||
"_This bot is free and_ [open source](https://github.com/LightningTipBot/LightningTipBot) _software. You can run it on your own computer and use it in your own community._\n\n" +
|
||||
"✈️ *Telegram*\n" +
|
||||
"_Add this bot to your Telegram group chat to /tip posts. If you make the bot admin of the group it will also clean up commands to keep the chat tidy._\n\n" +
|
||||
// "🏛 *Terms*\n" +
|
||||
// "_We are not custodian of your funds. Any amount you load onto your wallet will be legally considered a donation that belongs to us. We will act in your best interest but we're also aware that the situation without KYC is tricky until we figure something out. Do not give us all your money. Be aware that this bot is in beta development. Use at your own risk._\n\n" +
|
||||
"_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. That way you don't have to trust anyone to keep your funds safe._\n\n" +
|
||||
"❤️ *Donate*\n" +
|
||||
"_This bot charges no fees but costs satoshis to operate. If you like the bot, please consider supporting this project with a donation. To donate, To donate, use_ `/donate 1000`"
|
||||
|
||||
advancedMessage = "🤖 *Advanced commands*\n\n" +
|
||||
"*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)\n"
|
||||
"_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`"
|
||||
)
|
||||
|
||||
func (bot TipBot) helpHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
if !m.Private() {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
@@ -51,8 +40,6 @@ func (bot TipBot) helpHandler(m *tb.Message) {
|
||||
}
|
||||
|
||||
func (bot TipBot) infoHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
if !m.Private() {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
@@ -60,14 +47,3 @@ 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,9 +2,19 @@ package lnbits
|
||||
|
||||
import (
|
||||
"github.com/imroc/req"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
// NewClient returns a new lnbits api client. Pass your API key and url here.
|
||||
type Client struct {
|
||||
header req.Header
|
||||
url string
|
||||
AdminKey string
|
||||
InvoiceKey string
|
||||
}
|
||||
|
||||
// NewClient is the first function you must call. Pass your main API key here.
|
||||
// It will return a client you can later use to access wallets and transactions.
|
||||
// You can find it at https://lnpay.co/developers/dashboard
|
||||
func NewClient(key, url string) *Client {
|
||||
return &Client{
|
||||
url: url,
|
||||
@@ -16,7 +26,29 @@ func NewClient(key, url string) *Client {
|
||||
}
|
||||
}
|
||||
|
||||
// GetUser returns user information
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name" gorm:"primaryKey"`
|
||||
Initialized bool `json:"initialized"`
|
||||
Telegram *tb.User `gorm:"embedded;embeddedPrefix:telegram_"`
|
||||
Wallet *Wallet `gorm:"embedded;embeddedPrefix:wallet_"`
|
||||
StateKey UserStateKey `json:"stateKey"`
|
||||
StateData string `json:"stateData"`
|
||||
}
|
||||
type UserStateKey int
|
||||
|
||||
const (
|
||||
UserStateConfirmPayment = iota + 1
|
||||
)
|
||||
|
||||
func (u *User) ResetState() {
|
||||
u.StateData = ""
|
||||
u.StateKey = 0
|
||||
}
|
||||
|
||||
// CreateWallet creates a new wallet with a given descriptive label.
|
||||
// It will return the wallet object which you can use to create invoices and payments.
|
||||
// https://docs.lnpay.co/wallet/create-wallet
|
||||
func (c *Client) GetUser(userId string) (user User, err error) {
|
||||
resp, err := req.Post(c.url+"/usermanager/api/v1/users/"+userId, c.header, nil)
|
||||
if err != nil {
|
||||
@@ -34,7 +66,9 @@ func (c *Client) GetUser(userId string) (user User, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// CreateUserWithInitialWallet creates new user with initial wallet
|
||||
// CreateWallet creates a new wallet with a given descriptive label.
|
||||
// It will return the wallet object which you can use to create invoices and payments.
|
||||
// https://docs.lnpay.co/wallet/create-wallet
|
||||
func (c *Client) CreateUserWithInitialWallet(userName, walletName, adminId string, email string) (wal User, err error) {
|
||||
resp, err := req.Post(c.url+"/usermanager/api/v1/users", c.header, req.BodyJSON(struct {
|
||||
WalletName string `json:"wallet_name"`
|
||||
@@ -56,7 +90,9 @@ func (c *Client) CreateUserWithInitialWallet(userName, walletName, adminId strin
|
||||
return
|
||||
}
|
||||
|
||||
// CreateWallet creates a new wallet.
|
||||
// CreateWallet creates a new wallet with a given descriptive label.
|
||||
// It will return the wallet object which you can use to create invoices and payments.
|
||||
// https://docs.lnpay.co/wallet/create-wallet
|
||||
func (c *Client) CreateWallet(userId, walletName, adminId string) (wal Wallet, err error) {
|
||||
resp, err := req.Post(c.url+"/usermanager/api/v1/wallets", c.header, req.BodyJSON(struct {
|
||||
UserId string `json:"user_id"`
|
||||
@@ -78,7 +114,15 @@ func (c *Client) CreateWallet(userId, walletName, adminId string) (wal Wallet, e
|
||||
return
|
||||
}
|
||||
|
||||
type InvoiceParams struct {
|
||||
Out bool `json:"out"`
|
||||
Amount int64 `json:"amount"`
|
||||
Memo string `json:"memo"` // the invoice description.
|
||||
Webhook string `json:"webhook,omitempty"`
|
||||
}
|
||||
|
||||
// Invoice creates an invoice associated with this wallet.
|
||||
// https://docs.lnpay.co/wallet/generate-invoice
|
||||
func (c Client) Invoice(params InvoiceParams, w Wallet) (lntx BitInvoice, err error) {
|
||||
c.header["X-Api-Key"] = w.Adminkey
|
||||
resp, err := req.Post(c.url+"/api/v1/payments", w.header, req.BodyJSON(¶ms))
|
||||
@@ -97,7 +141,18 @@ func (c Client) Invoice(params InvoiceParams, w Wallet) (lntx BitInvoice, err er
|
||||
return
|
||||
}
|
||||
|
||||
// Info returns wallet information
|
||||
type PaymentParams struct {
|
||||
Out bool `json:"out"`
|
||||
Bolt11 string `json:"bolt11"`
|
||||
}
|
||||
type PayParams struct {
|
||||
// the BOLT11 payment request you want to pay.
|
||||
PaymentRequest string `json:"payment_request"`
|
||||
|
||||
// custom data you may want to associate with this invoice. optional.
|
||||
PassThru map[string]interface{} `json:"passThru"`
|
||||
}
|
||||
|
||||
func (c Client) Info(w Wallet) (wtx Wallet, err error) {
|
||||
c.header["X-Api-Key"] = w.Adminkey
|
||||
resp, err := req.Get(w.url+"/api/v1/wallet", w.header, nil)
|
||||
@@ -115,8 +170,6 @@ func (c Client) Info(w Wallet) (wtx Wallet, err error) {
|
||||
err = resp.ToJSON(&wtx)
|
||||
return
|
||||
}
|
||||
|
||||
// Wallets returns all wallets belonging to an user
|
||||
func (c Client) Wallets(w User) (wtx []Wallet, err error) {
|
||||
resp, err := req.Get(c.url+"/usermanager/api/v1/wallets/"+w.ID, c.header, nil)
|
||||
if err != nil {
|
||||
@@ -135,6 +188,7 @@ func (c Client) Wallets(w User) (wtx []Wallet, err error) {
|
||||
}
|
||||
|
||||
// Pay pays a given invoice with funds from the wallet.
|
||||
// https://docs.lnpay.co/wallet/pay-invoice
|
||||
func (c Client) Pay(params PaymentParams, w Wallet) (wtx BitInvoice, err error) {
|
||||
c.header["X-Api-Key"] = w.Adminkey
|
||||
resp, err := req.Post(c.url+"/api/v1/payments", w.header, req.BodyJSON(¶ms))
|
||||
@@ -152,3 +206,9 @@ func (c Client) Pay(params PaymentParams, w Wallet) (wtx BitInvoice, err error)
|
||||
err = resp.ToJSON(&wtx)
|
||||
return
|
||||
}
|
||||
|
||||
type TransferParams struct {
|
||||
Memo string `json:"memo"` // the transfer description.
|
||||
NumSatoshis int64 `json:"num_satoshis"` // the transfer amount.
|
||||
DestWalletId string `json:"dest_wallet_id"` // the key or id of the destination
|
||||
}
|
||||
|
||||
@@ -1,63 +1,5 @@
|
||||
package lnbits
|
||||
|
||||
import (
|
||||
"github.com/imroc/req"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
header req.Header
|
||||
url string
|
||||
AdminKey string
|
||||
InvoiceKey string
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name" gorm:"primaryKey"`
|
||||
Initialized bool `json:"initialized"`
|
||||
Telegram *tb.User `gorm:"embedded;embeddedPrefix:telegram_"`
|
||||
Wallet *Wallet `gorm:"embedded;embeddedPrefix:wallet_"`
|
||||
StateKey UserStateKey `json:"stateKey"`
|
||||
StateData string `json:"stateData"`
|
||||
}
|
||||
type UserStateKey int
|
||||
|
||||
const (
|
||||
UserStateConfirmPayment = iota + 1
|
||||
UserStateConfirmSend
|
||||
)
|
||||
|
||||
func (u *User) ResetState() {
|
||||
u.StateData = ""
|
||||
u.StateKey = 0
|
||||
}
|
||||
|
||||
type InvoiceParams struct {
|
||||
Out bool `json:"out"`
|
||||
Amount int64 `json:"amount"`
|
||||
Memo string `json:"memo"` // the invoice description.
|
||||
Webhook string `json:"webhook,omitempty"`
|
||||
}
|
||||
|
||||
type PaymentParams struct {
|
||||
Out bool `json:"out"`
|
||||
Bolt11 string `json:"bolt11"`
|
||||
}
|
||||
type PayParams struct {
|
||||
// the BOLT11 payment request you want to pay.
|
||||
PaymentRequest string `json:"payment_request"`
|
||||
|
||||
// custom data you may want to associate with this invoice. optional.
|
||||
PassThru map[string]interface{} `json:"passThru"`
|
||||
}
|
||||
|
||||
type TransferParams struct {
|
||||
Memo string `json:"memo"` // the transfer description.
|
||||
NumSatoshis int64 `json:"num_satoshis"` // the transfer amount.
|
||||
DestWalletId string `json:"dest_wallet_id"` // the key or id of the destination
|
||||
}
|
||||
|
||||
type Error struct {
|
||||
Name string `json:"name"`
|
||||
Message string `json:"message"`
|
||||
|
||||
@@ -82,10 +82,10 @@ func (w WebhookServer) receive(writer http.ResponseWriter, request *http.Request
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
log.Infoln(fmt.Sprintf("[WebHook] User %s (%d) received invoice of %d sat.", user.Telegram.Username, user.Telegram.ID, depositEvent.Amount/1000))
|
||||
log.Println(fmt.Sprintf("[WebHook] User %s (%d) received invoice of %d sat.", user.Telegram.Username, user.Telegram.ID, depositEvent.Amount/1000))
|
||||
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(invoiceReceivedMessage, depositEvent.Amount/1000))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
fmt.Println(err)
|
||||
}
|
||||
writer.WriteHeader(200)
|
||||
}
|
||||
|
||||
+8
-14
@@ -12,44 +12,38 @@ import (
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
invoiceEnterAmountMessage = "Did you enter an amount?"
|
||||
invoiceValidAmountMessage = "Did you enter a valid amount?"
|
||||
invoiceHelpText = "📖 Oops, that didn't work. %s\n\n" +
|
||||
func helpInvoiceUsage(errormsg string) string {
|
||||
helpstr := "📖 Oops, that didn't work. %s\n\n" +
|
||||
"*Usage:* `/invoice <amount> [<memo>]`\n" +
|
||||
"*Example:* `/invoice 1000 Take this! 💸`"
|
||||
)
|
||||
|
||||
func helpInvoiceUsage(errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(invoiceHelpText, fmt.Sprintf("%s", errormsg))
|
||||
helpstr = fmt.Sprintf(helpstr, fmt.Sprintf("_%s_", errormsg))
|
||||
} else {
|
||||
return fmt.Sprintf(invoiceHelpText, "")
|
||||
helpstr = fmt.Sprintf(helpstr, "")
|
||||
}
|
||||
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(invoiceEnterAmountMessage))
|
||||
bot.telegram.Send(m.Sender, helpInvoiceUsage(""))
|
||||
return
|
||||
}
|
||||
|
||||
user, err := GetUser(m.Sender, bot)
|
||||
userStr := GetUserStr(m.Sender)
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
amount, err := DecodeAmountFromCommand(m.Text)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if amount > 0 {
|
||||
} else {
|
||||
bot.telegram.Send(m.Sender, helpInvoiceUsage(invoiceValidAmountMessage))
|
||||
bot.telegram.Send(m.Sender, helpInvoiceUsage("Did you use a valid amount?"))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
walletConnectMessage = "🔗 *Link your wallet*\n\n" +
|
||||
"⚠️ Never share the URL or the QR code with anyone or they will be able to access your funds.\n\n" +
|
||||
"- *BlueWallet:* Press *New wallet*, *Import wallet*, *Scan or import a file*, and scan the QR code.\n" +
|
||||
"- *Zeus:* Copy the URL below, press *Add a new node*, *Import* (the URL), *Save Node Config*."
|
||||
)
|
||||
|
||||
func (bot TipBot) lndhubHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
// reply only in private message
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
}
|
||||
// first check whether the user is initialized
|
||||
fromUser, err := GetUser(m.Sender, bot)
|
||||
if err != nil {
|
||||
log.Errorf("[/balance] Error: %s", err)
|
||||
return
|
||||
}
|
||||
bot.telegram.Send(m.Sender, walletConnectMessage)
|
||||
|
||||
lnbitsUrl := Configuration.LnbitsPublicUrl
|
||||
if !strings.HasSuffix(lnbitsUrl, "/") {
|
||||
lnbitsUrl = lnbitsUrl + "/"
|
||||
}
|
||||
lndhubUrl := fmt.Sprintf("lndhub://admin:%s@%slndhub/ext/", fromUser.Wallet.Adminkey, lnbitsUrl)
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(lndhubUrl, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/invoice] Failed to create QR code for invoice: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
// send the invoice data to user
|
||||
bot.telegram.Send(m.Sender, &tb.Photo{File: tb.File{FileReader: bytes.NewReader(qr)}, Caption: fmt.Sprintf("`%s`", lndhubUrl)})
|
||||
}
|
||||
@@ -1,21 +1,10 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// setLogger will initialize the log format
|
||||
func setLogger() {
|
||||
log.SetLevel(log.InfoLevel)
|
||||
customFormatter := new(log.TextFormatter)
|
||||
customFormatter.TimestampFormat = "2006-01-02 15:04:05"
|
||||
customFormatter.FullTimestamp = true
|
||||
log.SetFormatter(customFormatter)
|
||||
}
|
||||
|
||||
func main() {
|
||||
// set logger
|
||||
setLogger()
|
||||
defer withRecovery()
|
||||
bot := NewBot()
|
||||
bot.Start()
|
||||
@@ -23,6 +12,6 @@ func main() {
|
||||
|
||||
func withRecovery() {
|
||||
if r := recover(); r != nil {
|
||||
log.Errorln("Recovered panic: ", r)
|
||||
fmt.Println("Recovered panic: ", r)
|
||||
}
|
||||
}
|
||||
|
||||
+118
-7
@@ -1,6 +1,8 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -44,6 +46,122 @@ func NewMessage(m *tb.Message, opts ...messageOption) *Message {
|
||||
|
||||
}
|
||||
|
||||
// updateToolTip updates existing tip tool tip in telegram
|
||||
func (x *Message) updateTooltip(bot *TipBot, user *tb.User, amount int, notInitializedWallet bool) {
|
||||
x.TipAmount += amount
|
||||
x.Ntips += 1
|
||||
x.Tippers = appendUinqueUsersToSlice(x.Tippers, user)
|
||||
x.LastTip = time.Now()
|
||||
userTips := bot.tips[x.Message.ReplyTo.Sender.ID]
|
||||
for _, tip := range userTips {
|
||||
if tip.Message.ReplyTo.Sender.ID == x.Message.ReplyTo.Sender.ID {
|
||||
err := x.editTooltip(bot, notInitializedWallet)
|
||||
if err != nil {
|
||||
log.Printf("[updateTooltip] could not edit tooltip: %s", err.Error())
|
||||
continue
|
||||
}
|
||||
tip = x
|
||||
}
|
||||
}
|
||||
bot.tips[x.Message.ReplyTo.Sender.ID] = userTips
|
||||
}
|
||||
func (x *Message) editTooltip(bot *TipBot, notInitializedWallet bool) error {
|
||||
tipToolTip := x.getTooltipMessage(GetUserStrMd(bot.telegram.Me), notInitializedWallet)
|
||||
m, err := bot.telegram.Edit(x.Message, tipToolTip)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Message.Text = m.Text
|
||||
return nil
|
||||
}
|
||||
func tipTooltipInitializedHandler(user *tb.User, bot TipBot) {
|
||||
for _, tip := range bot.tips[user.ID] {
|
||||
if tip.Message.ReplyTo.Sender.ID == user.ID {
|
||||
err := tip.editTooltip(&bot, false)
|
||||
if err != nil {
|
||||
log.Printf("[tipTooltipInitializedHandler] could not edit tooltip: %s", err.Error())
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// getTippersString joins all tippers username or telegram id's as mentions (@username or [inline mention of a user](tg://user?id=123456789))
|
||||
func getTippersString(tippers []*tb.User) string {
|
||||
var tippersStr string
|
||||
for _, uniqueUser := range tippers {
|
||||
userStr := GetUserStrMd(uniqueUser)
|
||||
tippersStr += fmt.Sprintf("%s, ", userStr)
|
||||
}
|
||||
// get rid of the trailing comma
|
||||
if len(tippersStr) > 2 {
|
||||
tippersStr = tippersStr[:len(tippersStr)-2]
|
||||
}
|
||||
tippersSlice := strings.Split(tippersStr, " ")
|
||||
// crop the message to the max length
|
||||
if len(tippersSlice) > maxNamesInTipperMessage {
|
||||
// tippersStr = tippersStr[:50]
|
||||
tippersStr = strings.Join(tippersSlice[:maxNamesInTipperMessage], " ")
|
||||
tippersStr = tippersStr + " ... and others"
|
||||
}
|
||||
return tippersStr
|
||||
}
|
||||
|
||||
// getTooltipMessage will return the full tip tool tip
|
||||
func (x Message) getTooltipMessage(botUserName string, notInitializedWallet bool) string {
|
||||
tippersStr := getTippersString(x.Tippers)
|
||||
tipToolTipMessage := fmt.Sprintf("🏅 %d sat", x.TipAmount)
|
||||
if len(x.Tippers) > 1 {
|
||||
tipToolTipMessage = fmt.Sprintf("%s (%d tips by %s)", tipToolTipMessage, x.Ntips, tippersStr)
|
||||
} else {
|
||||
tipToolTipMessage = fmt.Sprintf("%s (by %s)", tipToolTipMessage, tippersStr)
|
||||
}
|
||||
|
||||
if notInitializedWallet {
|
||||
tipToolTipMessage = tipToolTipMessage + fmt.Sprintf("\n🗑 Chat with %s to manage your wallet.", botUserName)
|
||||
}
|
||||
return tipToolTipMessage
|
||||
}
|
||||
|
||||
// tipTooltipExists checks if this tip is already known
|
||||
func tipTooltipExists(m *tb.Message, bot *TipBot) (bool, *Message) {
|
||||
for _, tip := range bot.tips[m.ReplyTo.Sender.ID] {
|
||||
if tip.Message.ReplyTo != nil && m.ReplyTo != nil {
|
||||
if tip.Message.ReplyTo.ID == m.ReplyTo.ID {
|
||||
return true, tip
|
||||
}
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// tipTooltipHandler function to update the tooltip below a tipped message. either updates or creates initial tip tool tip
|
||||
func tipTooltipHandler(m *tb.Message, user *tb.User, bot *TipBot, amount int, notInitializedWallet bool) bool {
|
||||
// todo: this crashes if the tooltip message (maybe also the original tipped message) was deleted in the mean time!!! need to check for existence!
|
||||
ok, tipMessage := tipTooltipExists(m, bot)
|
||||
if ok {
|
||||
// update the tooltip with new tippers
|
||||
tipMessage.updateTooltip(bot, user, amount, notInitializedWallet)
|
||||
} else {
|
||||
tipmsg := fmt.Sprintf("🏅 %d sat", amount)
|
||||
userStr := GetUserStrMd(user)
|
||||
tipmsg = fmt.Sprintf("%s (by %s)", tipmsg, userStr)
|
||||
|
||||
if notInitializedWallet {
|
||||
tipmsg = tipmsg + fmt.Sprintf("\n🗑 Chat with %s to manage your wallet.", GetUserStrMd(bot.telegram.Me))
|
||||
}
|
||||
msg, err := bot.telegram.Reply(m.ReplyTo, tipmsg)
|
||||
if err != nil {
|
||||
print(err)
|
||||
}
|
||||
message := NewMessage(msg, TipAmount(amount), Tips(1))
|
||||
message.Tippers = appendUinqueUsersToSlice(message.Tippers, user)
|
||||
bot.tips[m.ReplyTo.Sender.ID] = append(bot.tips[m.ReplyTo.Sender.ID], message)
|
||||
}
|
||||
// first call will return false, every following call will return true
|
||||
return ok
|
||||
}
|
||||
|
||||
func (x Message) Dispose(duration time.Duration, telegram *tb.Bot) {
|
||||
// do not delete messages from private chat
|
||||
if x.Message.Private() {
|
||||
@@ -58,10 +176,3 @@ func (x Message) Dispose(duration time.Duration, telegram *tb.Bot) {
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func removeMessage(messages []*Message, s int) []*Message {
|
||||
if len(messages) == 1 {
|
||||
return make([]*Message, 0)
|
||||
}
|
||||
return append(messages[:s], messages[s+1:]...)
|
||||
}
|
||||
|
||||
@@ -17,11 +17,9 @@ const (
|
||||
invoicePrivateChatOnlyErrorMessage = "You can pay invoices only in the private chat with the bot."
|
||||
invalidInvoiceHelpMessage = "Did you enter a valid Lightning invoice?"
|
||||
invoiceNoAmountMessage = "🚫 Can't pay invoices without an amount."
|
||||
insufficientFundsMessage = "🚫 Insufficient funds. You have %d sat but you need at least %d sat."
|
||||
feeReserveMessage = "⚠️ Sending your entire balance might fail because of network fees. If it fails, try sending a bit less."
|
||||
insufficiendFundsMessage = "🚫 Insufficient funds. You have %d sat but you need at least %d sat."
|
||||
invoicePaymentFailedMessage = "🚫 Failed to pay invoice: %s"
|
||||
confirmPayInvoiceMessage = "Do you want to pay this invoice?\n\n💸 Amount: %d sat"
|
||||
confirmPayAppendMemo = "\n✉️ %s"
|
||||
confirmPayInvoiceMessage = "Do you want to pay this invoice?\n💸 Amount: %d sat\n✉️ %s"
|
||||
payHelpText = "📖 Oops, that didn't work. %s\n\n" +
|
||||
"*Usage:* `/pay <invoice>`\n" +
|
||||
"*Example:* `/pay lnbc20n1psscehd...`"
|
||||
@@ -29,7 +27,7 @@ const (
|
||||
|
||||
func helpPayInvoiceUsage(errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(payHelpText, fmt.Sprintf("%s", errormsg))
|
||||
return fmt.Sprintf(payHelpText, fmt.Sprintf("_%s_", errormsg))
|
||||
} else {
|
||||
return fmt.Sprintf(payHelpText, "")
|
||||
}
|
||||
@@ -37,8 +35,6 @@ func helpPayInvoiceUsage(errormsg string) string {
|
||||
|
||||
// confirmPaymentHandler invoked on "/pay lnbc..." command
|
||||
func (bot TipBot) confirmPaymentHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
// delete message
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
@@ -51,27 +47,14 @@ func (bot TipBot) confirmPaymentHandler(m *tb.Message) {
|
||||
return
|
||||
}
|
||||
user, err := GetUser(m.Sender, bot)
|
||||
if err != nil {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not GetUser: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
userStr := GetUserStr(m.Sender)
|
||||
paymentRequest, err := getArgumentFromCommand(m.Text, 1)
|
||||
if err != nil {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
bot.telegram.Send(m.Sender, helpPayInvoiceUsage(invalidInvoiceHelpMessage))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not getArgumentFromCommand: %s", err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
paymentRequest = strings.ToLower(paymentRequest)
|
||||
payment_request, err := getArgumentFromCommand(m.Text, 1)
|
||||
payment_request = strings.ToLower(payment_request)
|
||||
// get rid of the URI prefix
|
||||
paymentRequest = strings.TrimPrefix(paymentRequest, "lightning:")
|
||||
payment_request = strings.TrimPrefix(payment_request, "lightning:")
|
||||
|
||||
// decode invoice
|
||||
bolt11, err := decodepay.Decodepay(paymentRequest)
|
||||
bolt11, err := decodepay.Decodepay(payment_request)
|
||||
if err != nil {
|
||||
bot.telegram.Send(m.Sender, helpPayInvoiceUsage(invalidInvoiceHelpMessage))
|
||||
errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err)
|
||||
@@ -80,12 +63,14 @@ func (bot TipBot) confirmPaymentHandler(m *tb.Message) {
|
||||
}
|
||||
amount := int(bolt11.MSatoshi / 1000)
|
||||
|
||||
if amount <= 0 {
|
||||
if !(amount > 0) {
|
||||
bot.telegram.Send(m.Sender, invoiceNoAmountMessage)
|
||||
errmsg := fmt.Sprint("[/pay] Error: invoice without amount")
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
// description := bolt11.Description
|
||||
// log.Printf("[Pay Invoice] Description: %s", description)
|
||||
|
||||
// check user balance first
|
||||
balance, err := bot.GetUserBalance(m.Sender)
|
||||
@@ -97,43 +82,42 @@ func (bot TipBot) confirmPaymentHandler(m *tb.Message) {
|
||||
}
|
||||
if amount > balance {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf(insufficientFundsMessage, balance, amount))
|
||||
bot.telegram.Send(m.Sender, helpPayInvoiceUsage(fmt.Sprintf(insufficiendFundsMessage, balance, amount)))
|
||||
return
|
||||
}
|
||||
// send warning that the invoice might fail due to missing fee reserve
|
||||
if float64(amount) > float64(balance)*0.99 {
|
||||
bot.telegram.Send(m.Sender, feeReserveMessage)
|
||||
}
|
||||
|
||||
log.Printf("[/pay] User: %s, amount: %d sat.", userStr, amount)
|
||||
user.StateKey = lnbits.UserStateConfirmPayment
|
||||
user.StateData = paymentRequest
|
||||
user.StateData = payment_request
|
||||
err = UpdateUserRecord(user, bot)
|
||||
if err != nil {
|
||||
log.Printf("[UpdateUserRecord] User: %s Error: %s", userStr, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// // // create inline buttons
|
||||
paymentConfirmationMenu.Inline(paymentConfirmationMenu.Row(btnPay, btnCancelPay))
|
||||
confirmText := fmt.Sprintf(confirmPayInvoiceMessage, amount)
|
||||
if len(bolt11.Description) > 0 {
|
||||
confirmText = confirmText + fmt.Sprintf(confirmPayAppendMemo, MarkdownEscape(bolt11.Description))
|
||||
// paymentConfirmationMenu := &tb.ReplyMarkup{ResizeReplyKeyboard: true}
|
||||
// btnPay := paymentConfirmationMenu.Data(fmt.Sprintf("✅ Pay %d sat", amount), "pay")
|
||||
// btnCancel := paymentConfirmationMenu.Data("🚫 Cancel payment", "cancel")
|
||||
|
||||
paymentConfirmationMenu.Inline(paymentConfirmationMenu.Row(btnPay, btnCancel))
|
||||
bot.telegram.Send(m.Sender,
|
||||
// fmt.Sprintf("*Amount:* %d sat\n✉️ %s\n*Hash:* %s\nCreatedAt: %s\nPayee: %s\n", bolt11.MSatoshi/1000, bolt11.Description, bolt11.PaymentHash, time.Unix(int64(bolt11.CreatedAt), 0).String(), bolt11.Payee),
|
||||
fmt.Sprintf(confirmPayInvoiceMessage, bolt11.MSatoshi/1000, bolt11.Description),
|
||||
paymentConfirmationMenu)
|
||||
if err != nil {
|
||||
log.Printf("[UpdateUserRecord] User: %s Error: %s", userStr, err.Error())
|
||||
}
|
||||
bot.telegram.Send(m.Sender, confirmText, paymentConfirmationMenu)
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot TipBot) cancelPaymentHandler(c *tb.Callback) {
|
||||
// reset state immediately
|
||||
defer func() {
|
||||
bot.telegram.Delete(c.Message)
|
||||
}()
|
||||
user, err := GetUser(c.Sender, bot)
|
||||
if err != nil {
|
||||
log.Printf("[GetUser] User: %d: %s", c.Sender.ID, err.Error())
|
||||
return
|
||||
}
|
||||
user.ResetState()
|
||||
err = UpdateUserRecord(user, bot)
|
||||
|
||||
bot.telegram.Delete(c.Message)
|
||||
_, err = bot.telegram.Send(c.Sender, paymentCancelledMessage)
|
||||
if err != nil {
|
||||
log.WithField("message", paymentCancelledMessage).WithField("user", c.Sender.ID).Printf("[Send] %s", err.Error())
|
||||
@@ -144,22 +128,18 @@ func (bot TipBot) cancelPaymentHandler(c *tb.Callback) {
|
||||
|
||||
// payHandler when user clicked pay "X" on payment confirmation
|
||||
func (bot TipBot) payHandler(c *tb.Callback) {
|
||||
bot.telegram.Edit(c.Message, c.Message.Text, &tb.ReplyMarkup{})
|
||||
defer func() {
|
||||
bot.telegram.Edit(c.Message, c.Message.Text, &tb.ReplyMarkup{})
|
||||
}()
|
||||
user, err := GetUser(c.Sender, bot)
|
||||
if err != nil {
|
||||
log.Printf("[GetUser] User: %d: %s", c.Sender.ID, err.Error())
|
||||
return
|
||||
}
|
||||
if user.StateKey == lnbits.UserStateConfirmPayment {
|
||||
invoiceString := user.StateData
|
||||
|
||||
// reset state immediatelly
|
||||
user.ResetState()
|
||||
err = UpdateUserRecord(user, bot)
|
||||
|
||||
userStr := GetUserStr(c.Sender)
|
||||
// pay invoice
|
||||
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: invoiceString}, *user.Wallet)
|
||||
invoice, err := user.Wallet.Pay(lnbits.PaymentParams{Out: true, Bolt11: user.StateData}, *user.Wallet)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/pay] Could not pay invoice of user %s: %s", userStr, err)
|
||||
bot.telegram.Send(c.Sender, fmt.Sprintf(invoicePaymentFailedMessage, err))
|
||||
@@ -168,6 +148,8 @@ func (bot TipBot) payHandler(c *tb.Callback) {
|
||||
}
|
||||
bot.telegram.Send(c.Sender, invoicePaidMessage)
|
||||
log.Printf("[/pay] User %s paid invoice %s", userStr, invoice.PaymentHash)
|
||||
user.ResetState()
|
||||
err = UpdateUserRecord(user, bot)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
"github.com/makiuchi-d/gozxing"
|
||||
"github.com/makiuchi-d/gozxing/qrcode"
|
||||
log "github.com/sirupsen/logrus"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
photoQrNotRecognizedMessage = "🚫 Could not regocognize a Lightning invoice. Try to center the QR code, crop the photo, or zoom in."
|
||||
photoInvoiceRecognizedMessage = "✅ Invoice:\n`%s`"
|
||||
)
|
||||
|
||||
// TryRecognizeInvoiceFromQrCode will try to read an invoice string from a qr code and invoke the payment handler.
|
||||
func TryRecognizeInvoiceFromQrCode(img image.Image) (*gozxing.Result, error) {
|
||||
// check for qr code
|
||||
bmp, _ := gozxing.NewBinaryBitmapFromImage(img)
|
||||
// decode image
|
||||
qrReader := qrcode.NewQRCodeReader()
|
||||
result, err := qrReader.Decode(bmp, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload := strings.ToLower(result.String())
|
||||
if lightning.IsInvoice(payload) {
|
||||
// create payment command payload
|
||||
// invoke payment confirmation handler
|
||||
return result, nil
|
||||
}
|
||||
return nil, fmt.Errorf("no codes found")
|
||||
}
|
||||
|
||||
// privatePhotoHandler is the handler function for every photo from a private chat that the bot receives
|
||||
func (bot TipBot) privatePhotoHandler(m *tb.Message) {
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return
|
||||
}
|
||||
if m.Photo == nil {
|
||||
return
|
||||
}
|
||||
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, "<Photo>")
|
||||
// get file reader closer from telegram api
|
||||
reader, err := bot.telegram.GetFile(m.Photo.MediaFile())
|
||||
if err != nil {
|
||||
log.Errorf("Getfile error: %v\n", err)
|
||||
return
|
||||
}
|
||||
// decode to jpeg image
|
||||
img, err := jpeg.Decode(reader)
|
||||
if err != nil {
|
||||
log.Errorf("image.Decode error: %v\n", err)
|
||||
return
|
||||
}
|
||||
data, err := TryRecognizeInvoiceFromQrCode(img)
|
||||
if err != nil {
|
||||
log.Errorf("tryRecognizeQrCodes error: %v\n", err)
|
||||
bot.telegram.Send(m.Sender, photoQrNotRecognizedMessage)
|
||||
return
|
||||
}
|
||||
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf(photoInvoiceRecognizedMessage, data.String()))
|
||||
|
||||
// invoke payment handler
|
||||
m.Text = fmt.Sprintf("/pay %s", data.String())
|
||||
bot.confirmPaymentHandler(m)
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package lightning
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// IsInvoice is used to check if a string matches lnbc invoide pattern.
|
||||
// todo -- probably should add regex and validate length
|
||||
func IsInvoice(invoice string) bool {
|
||||
// invoice string must start with lnbc or lightning:lnbc
|
||||
if strings.HasPrefix(invoice, "lnbc") || strings.HasPrefix(invoice, "lightning:lnbc") {
|
||||
// invoice string must be a single word
|
||||
if !strings.Contains(invoice, " ") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 172 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 55 KiB |
@@ -2,7 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -12,17 +11,13 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
sendValidAmountMessage = "Did you enter a valid amount?"
|
||||
sendValidAmountMessage = "Did you use 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."
|
||||
sendIsNotAUsser = "%s is not a user"
|
||||
sendUserHasNoWalletMessage = "🚫 User %s hasn't created a wallet yet."
|
||||
sendSentMessage = "💸 %d sat sent to %s."
|
||||
sendReceivedMessage = "🏅 %s has sent you %d sat."
|
||||
sendErrorMessage = "🚫 Transaction failed: %s"
|
||||
confirmSendInvoiceMessage = "Do you want to pay to %s?\n\n💸 Amount: %d sat"
|
||||
confirmSendAppendMemo = "\n✉️ %s"
|
||||
sendCancelledMessage = "🚫 Send cancelled."
|
||||
errorTryLaterMessage = "🚫 Internal error. Please try again later.."
|
||||
sendHelpText = "📖 Oops, that didn't work. %s\n\n" +
|
||||
"*Usage:* `/send <amount> <user> [<memo>]`\n" +
|
||||
"*Example:* `/send 1000 @LightningTipBot I just like the bot ❤️`"
|
||||
@@ -30,7 +25,7 @@ const (
|
||||
|
||||
func helpSendUsage(errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(sendHelpText, fmt.Sprintf("%s", errormsg))
|
||||
return fmt.Sprintf(sendHelpText, fmt.Sprintf("_%s_", errormsg))
|
||||
} else {
|
||||
return fmt.Sprintf(sendHelpText, "")
|
||||
}
|
||||
@@ -50,10 +45,7 @@ func SendCheckSyntax(m *tb.Message) (bool, string) {
|
||||
return true, ""
|
||||
}
|
||||
|
||||
// confirmPaymentHandler invoked on "/send 123 @user" command
|
||||
func (bot *TipBot) confirmSendHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
func (bot *TipBot) sendHandler(m *tb.Message) {
|
||||
// If the send is a reply, then trigger /tip handler
|
||||
if m.IsReply() {
|
||||
bot.tipHandler(m)
|
||||
@@ -67,7 +59,7 @@ func (bot *TipBot) confirmSendHandler(m *tb.Message) {
|
||||
}
|
||||
|
||||
// get send amount
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
amount, err := DecodeAmountFromCommand(m.Text)
|
||||
if err != nil || amount < 1 {
|
||||
errmsg := fmt.Sprintf("[/send] Error: Send amount not valid.")
|
||||
log.Errorln(errmsg)
|
||||
@@ -89,13 +81,13 @@ func (bot *TipBot) confirmSendHandler(m *tb.Message) {
|
||||
}
|
||||
}
|
||||
|
||||
// get *to* user
|
||||
// user must be mentioned in telegram as @username
|
||||
if len(m.Entities) < 2 {
|
||||
arg, err := getArgumentFromCommand(m.Text, 2)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
arg = MarkdownEscape(arg)
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
errmsg := fmt.Sprintf("Error: User %s could not be found", arg)
|
||||
bot.telegram.Send(m.Sender, helpSendUsage(fmt.Sprintf(sendUserNotFoundMessage, arg, arg)))
|
||||
@@ -107,13 +99,11 @@ func (bot *TipBot) confirmSendHandler(m *tb.Message) {
|
||||
arg, err := getArgumentFromCommand(m.Text, 2)
|
||||
if err != nil {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
arg = MarkdownEscape(arg)
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
errmsg := fmt.Sprintf("Error: %s is not a user", arg)
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf(sendIsNotAUsser, arg, arg))
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf(sendIsNotAUsser, arg))
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
}
|
||||
@@ -121,11 +111,6 @@ 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 {
|
||||
@@ -136,119 +121,9 @@ func (bot *TipBot) confirmSendHandler(m *tb.Message) {
|
||||
return
|
||||
}
|
||||
|
||||
// string that holds all information about the send payment
|
||||
sendData := strconv.Itoa(toUserDb.Telegram.ID) + "|" + toUserStrWithoutAt + "|" +
|
||||
strconv.Itoa(amount)
|
||||
if len(sendMemo) > 0 {
|
||||
sendData = sendData + "|" + sendMemo
|
||||
}
|
||||
|
||||
// save the send data to the database
|
||||
log.Debug(sendData)
|
||||
user, err := GetUser(m.Sender, *bot)
|
||||
if err != nil {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
log.Printf("[/send] Error: %s\n", err.Error())
|
||||
bot.telegram.Send(m.Sender, fmt.Sprint(errorTryLaterMessage))
|
||||
return
|
||||
}
|
||||
user.StateKey = lnbits.UserStateConfirmSend
|
||||
user.StateData = sendData
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
if err != nil {
|
||||
log.Printf("[UpdateUserRecord] User: %s Error: %s", GetUserStr(m.Sender), err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
sendConfirmationMenu.Inline(sendConfirmationMenu.Row(btnSend, btnCancelSend))
|
||||
confirmText := fmt.Sprintf(confirmSendInvoiceMessage, MarkdownEscape(toUserStrMention), amount)
|
||||
if len(sendMemo) > 0 {
|
||||
confirmText = confirmText + fmt.Sprintf(confirmSendAppendMemo, MarkdownEscape(sendMemo))
|
||||
}
|
||||
_, err = bot.telegram.Send(m.Sender, confirmText, sendConfirmationMenu)
|
||||
if err != nil {
|
||||
log.Error("[confirmSendHandler]" + err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// cancelPaymentHandler invoked when user clicked cancel on payment confirmation
|
||||
func (bot *TipBot) cancelSendHandler(c *tb.Callback) {
|
||||
// reset state immediately
|
||||
user, err := GetUser(c.Sender, *bot)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
user.ResetState()
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
// delete the confirmation message
|
||||
err = bot.telegram.Delete(c.Message)
|
||||
if err != nil {
|
||||
log.Errorln("[cancelSendHandler] " + err.Error())
|
||||
}
|
||||
// notify the user
|
||||
_, err = bot.telegram.Send(c.Sender, sendCancelledMessage)
|
||||
if err != nil {
|
||||
log.WithField("message", sendCancelledMessage).WithField("user", c.Sender.ID).Printf("[Send] %s", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// sendHandler invoked when user clicked send on payment confirmation
|
||||
func (bot *TipBot) sendHandler(c *tb.Callback) {
|
||||
// remove buttons from confirmation message
|
||||
_, err := bot.telegram.Edit(c.Message, MarkdownEscape(c.Message.Text), &tb.ReplyMarkup{})
|
||||
if err != nil {
|
||||
log.Errorln("[sendHandler] " + err.Error())
|
||||
}
|
||||
// decode callback data
|
||||
// log.Debug("[sendHandler] Callback: %s", c.Data)
|
||||
user, err := GetUser(c.Sender, *bot)
|
||||
if err != nil {
|
||||
log.Printf("[GetUser] User: %d: %s", c.Sender.ID, err.Error())
|
||||
return
|
||||
}
|
||||
if user.StateKey != lnbits.UserStateConfirmSend {
|
||||
log.Errorf("[sendHandler] User StateKey does not match! User: %d: StateKey: %d", c.Sender.ID, user.StateKey)
|
||||
return
|
||||
}
|
||||
|
||||
// decode StateData in which we have information about the send payment
|
||||
splits := strings.Split(user.StateData, "|")
|
||||
if len(splits) < 3 {
|
||||
log.Error("[sendHandler] Not enough arguments in callback data")
|
||||
log.Errorf("user.StateData: %s", user.StateData)
|
||||
return
|
||||
}
|
||||
toId, err := strconv.Atoi(splits[0])
|
||||
if err != nil {
|
||||
log.Errorln("[sendHandler] " + err.Error())
|
||||
}
|
||||
toUserStrWithoutAt := splits[1]
|
||||
amount, err := strconv.Atoi(splits[2])
|
||||
if err != nil {
|
||||
log.Errorln("[sendHandler] " + err.Error())
|
||||
}
|
||||
sendMemo := ""
|
||||
if len(splits) > 3 {
|
||||
sendMemo = strings.Join(splits[3:], "|")
|
||||
}
|
||||
|
||||
// reset state
|
||||
user.ResetState()
|
||||
err = UpdateUserRecord(user, *bot)
|
||||
if err != nil {
|
||||
log.Errorln(err.Error())
|
||||
return
|
||||
}
|
||||
// we can now get the wallets of both users
|
||||
to := &tb.User{ID: toId, Username: toUserStrWithoutAt}
|
||||
from := c.Sender
|
||||
to := &tb.User{ID: toUserDb.Telegram.ID, Username: toUserStrWithoutAt}
|
||||
from := m.Sender
|
||||
toUserStrMd := GetUserStrMd(to)
|
||||
fromUserStrMd := GetUserStrMd(from)
|
||||
toUserStr := GetUserStr(to)
|
||||
@@ -259,9 +134,9 @@ func (bot *TipBot) sendHandler(c *tb.Callback) {
|
||||
t.Memo = transactionMemo
|
||||
|
||||
success, err := t.Send()
|
||||
if !success || err != nil {
|
||||
// NewMessage(m).Dispose(0, bot.telegram)
|
||||
bot.telegram.Send(c.Sender, fmt.Sprintf(sendErrorMessage, err))
|
||||
if !success {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf(sendErrorMessage, err))
|
||||
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err)
|
||||
log.Errorln(errmsg)
|
||||
return
|
||||
@@ -269,10 +144,10 @@ func (bot *TipBot) sendHandler(c *tb.Callback) {
|
||||
|
||||
bot.telegram.Send(from, fmt.Sprintf(sendSentMessage, amount, toUserStrMd))
|
||||
bot.telegram.Send(to, fmt.Sprintf(sendReceivedMessage, fromUserStrMd, amount))
|
||||
|
||||
// send memo if it was present
|
||||
if len(sendMemo) > 0 {
|
||||
bot.telegram.Send(to, fmt.Sprintf("✉️ %s", MarkdownEscape(sendMemo)))
|
||||
bot.telegram.Send(to, fmt.Sprintf("✉️ %s", sendMemo))
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -15,30 +15,25 @@ 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."
|
||||
startNoUsernameMessage = "☝️ It looks like you don't have a Telegram @username yet. You don't need one to use this bot. However, to make better use of your new wallet, please set up a username in the [Telegram settings](https://telegram.org/faq#q-what-are-usernames-how-do-i-get-one). Then, enter /balance so the bot can update its record of you."
|
||||
)
|
||||
|
||||
func (bot TipBot) startHandler(m *tb.Message) {
|
||||
if !m.Private() {
|
||||
return
|
||||
}
|
||||
// ATTENTION: DO NOT CALL ANY HANDLER BEFORE THE WALLET IS CREATED
|
||||
// WILL RESULT IN AN ENDLESS LOOP OTHERWISE
|
||||
// bot.helpHandler(m)
|
||||
bot.telegram.Send(m.Sender, helpMessage, tb.NoPreview)
|
||||
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.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)
|
||||
}
|
||||
@@ -60,7 +55,6 @@ 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)
|
||||
@@ -68,12 +62,6 @@ 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,35 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
const (
|
||||
initWalletMessage = "You don't have a wallet yet. Enter */start*"
|
||||
)
|
||||
|
||||
func (bot TipBot) anyTextHandler(m *tb.Message) {
|
||||
log.Infof("[%s:%d %s:%d] %s", m.Chat.Title, m.Chat.ID, GetUserStr(m.Sender), m.Sender.ID, m.Text)
|
||||
if m.Chat.Type != tb.ChatPrivate {
|
||||
return
|
||||
}
|
||||
|
||||
// check if user is in database, if not, initialize wallet
|
||||
if !bot.UserHasWallet(m.Sender) {
|
||||
bot.startHandler(m)
|
||||
return
|
||||
}
|
||||
|
||||
// could be an invoice
|
||||
invoiceString := strings.ToLower(m.Text)
|
||||
if lightning.IsInvoice(invoiceString) {
|
||||
m.Text = "/pay " + invoiceString
|
||||
bot.confirmPaymentHandler(m)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -11,12 +11,12 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
tipDidYouReplyMessage = "Did you reply to a message to tip? To reply to any message, right-click -> Reply on your computer or swipe the message on your phone. If you want to send directly to another Telegram user's wallet, use the /send command."
|
||||
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."
|
||||
tipEnterAmountMessage = "Did you enter an amount?"
|
||||
tipValidAmountMessage = "Did you enter a valid amount?"
|
||||
tipValidAmountMessage = "Did you use a valid amount?"
|
||||
tipYourselfMessage = "📖 You can't tip yourself."
|
||||
tipSentMessage = "💸 %d sat sent to %s."
|
||||
tipReceivedMessage = "🏅 %s has tipped you %d sat."
|
||||
tipReceivedMessage = "🏅 You've received a %d sat tip from %s."
|
||||
tipErrorMessage = "🚫 Transaction failed: %s"
|
||||
tipHelpText = "📖 Oops, that didn't work. %s\n\n" +
|
||||
"*Usage:* `/tip <amount> [<memo>]`\n" +
|
||||
@@ -25,7 +25,7 @@ const (
|
||||
|
||||
func helpTipUsage(errormsg string) string {
|
||||
if len(errormsg) > 0 {
|
||||
return fmt.Sprintf(tipHelpText, fmt.Sprintf("%s", errormsg))
|
||||
return fmt.Sprintf(tipHelpText, fmt.Sprintf("_%s_", errormsg))
|
||||
} else {
|
||||
return fmt.Sprintf(tipHelpText, "")
|
||||
}
|
||||
@@ -40,8 +40,6 @@ func TipCheckSyntax(m *tb.Message) (bool, string) {
|
||||
}
|
||||
|
||||
func (bot *TipBot) tipHandler(m *tb.Message) {
|
||||
// check and print all commands
|
||||
bot.anyTextHandler(m)
|
||||
// only if message is a reply
|
||||
if !m.IsReply() {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
@@ -56,7 +54,7 @@ func (bot *TipBot) tipHandler(m *tb.Message) {
|
||||
}
|
||||
|
||||
// get tip amount
|
||||
amount, err := decodeAmountFromCommand(m.Text)
|
||||
amount, err := DecodeAmountFromCommand(m.Text)
|
||||
if err != nil || amount < 1 {
|
||||
errmsg := fmt.Sprintf("[/tip] Error: Tip amount not valid.")
|
||||
// immediately delete if the amount is bullshit
|
||||
@@ -66,10 +64,6 @@ func (bot *TipBot) tipHandler(m *tb.Message) {
|
||||
return
|
||||
}
|
||||
|
||||
err = bot.parseCmdDonHandler(m)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
// TIP COMMAND IS VALID
|
||||
|
||||
to := m.ReplyTo.Sender
|
||||
@@ -88,7 +82,7 @@ func (bot *TipBot) tipHandler(m *tb.Message) {
|
||||
|
||||
if !bot.UserHasWallet(to) {
|
||||
log.Infof("[/tip] User %s has no wallet.", toUserStr)
|
||||
err = bot.CreateWalletForTelegramUser(to)
|
||||
err = bot.CreateWalletForUser(to)
|
||||
if err != nil {
|
||||
errmsg := fmt.Errorf("[/tip] Error: Could not create wallet for %s", toUserStr)
|
||||
log.Errorln(errmsg)
|
||||
@@ -113,12 +107,12 @@ func (bot *TipBot) tipHandler(m *tb.Message) {
|
||||
success, err := t.Send()
|
||||
if !success {
|
||||
NewMessage(m).Dispose(0, bot.telegram)
|
||||
if err != nil {
|
||||
if len(err.Error()) > 0 {
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf(tipErrorMessage, err))
|
||||
} else {
|
||||
bot.telegram.Send(m.Sender, fmt.Sprintf(tipErrorMessage, "please try again later"))
|
||||
}
|
||||
errMsg := fmt.Sprintf("[/tip] Transaction failed: %s", err)
|
||||
errMsg := fmt.Sprintf("[/tip] Error: Transaction failed: %s", err)
|
||||
log.Errorln(errMsg)
|
||||
return
|
||||
}
|
||||
@@ -143,10 +137,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, fromUserStrMd, amount))
|
||||
bot.telegram.Send(to, fmt.Sprintf(tipReceivedMessage, amount, fromUserStrMd))
|
||||
|
||||
if len(tipMemo) > 0 {
|
||||
bot.telegram.Send(to, fmt.Sprintf("✉️ %s", MarkdownEscape(tipMemo)))
|
||||
bot.telegram.Send(to, fmt.Sprintf("✉️ %s", tipMemo))
|
||||
}
|
||||
|
||||
return
|
||||
|
||||
-149
@@ -1,149 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
)
|
||||
|
||||
func (bot *TipBot) cleanupTipsFromMemory() {
|
||||
go func() {
|
||||
defer withRecovery()
|
||||
for {
|
||||
for userId, userTips := range bot.tips {
|
||||
for i, tip := range userTips {
|
||||
if time.Now().Sub(tip.LastTip) > (time.Hour*24)*7 {
|
||||
userTips = removeMessage(userTips, i)
|
||||
err := bot.telegram.Delete(tip.Message)
|
||||
if err != nil {
|
||||
log.WithField("error", err.Error()).Error("could not delete tip tool tip")
|
||||
}
|
||||
bot.tips[userId] = userTips
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
time.Sleep(time.Hour)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// updateToolTip updates existing tip tool tip in telegram
|
||||
func (x *Message) updateTooltip(bot *TipBot, user *tb.User, amount int, notInitializedWallet bool) {
|
||||
x.TipAmount += amount
|
||||
x.Ntips += 1
|
||||
x.Tippers = appendUinqueUsersToSlice(x.Tippers, user)
|
||||
x.LastTip = time.Now()
|
||||
userTips := bot.tips[x.Message.ReplyTo.Sender.ID]
|
||||
for _, tip := range userTips {
|
||||
if tip.Message.ReplyTo.Sender.ID == x.Message.ReplyTo.Sender.ID {
|
||||
err := x.editTooltip(bot, notInitializedWallet)
|
||||
if err != nil {
|
||||
log.Printf("[updateTooltip] could not edit tooltip: %s", err.Error())
|
||||
continue
|
||||
}
|
||||
tip = x
|
||||
}
|
||||
}
|
||||
bot.tips[x.Message.ReplyTo.Sender.ID] = userTips
|
||||
}
|
||||
func (x *Message) editTooltip(bot *TipBot, notInitializedWallet bool) error {
|
||||
tipToolTip := x.getTooltipMessage(GetUserStrMd(bot.telegram.Me), notInitializedWallet)
|
||||
m, err := bot.telegram.Edit(x.Message, tipToolTip)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.Message.Text = m.Text
|
||||
return nil
|
||||
}
|
||||
func tipTooltipInitializedHandler(user *tb.User, bot TipBot) {
|
||||
for _, tip := range bot.tips[user.ID] {
|
||||
if tip.Message.ReplyTo.Sender.ID == user.ID {
|
||||
err := tip.editTooltip(&bot, false)
|
||||
if err != nil {
|
||||
log.Printf("[tipTooltipInitializedHandler] could not edit tooltip: %s", err.Error())
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// getTippersString joins all tippers username or telegram id's as mentions (@username or [inline mention of a user](tg://user?id=123456789))
|
||||
func getTippersString(tippers []*tb.User) string {
|
||||
var tippersStr string
|
||||
for _, uniqueUser := range tippers {
|
||||
userStr := GetUserStrMd(uniqueUser)
|
||||
tippersStr += fmt.Sprintf("%s, ", userStr)
|
||||
}
|
||||
// get rid of the trailing comma
|
||||
if len(tippersStr) > 2 {
|
||||
tippersStr = tippersStr[:len(tippersStr)-2]
|
||||
}
|
||||
tippersSlice := strings.Split(tippersStr, " ")
|
||||
// crop the message to the max length
|
||||
if len(tippersSlice) > maxNamesInTipperMessage {
|
||||
// tippersStr = tippersStr[:50]
|
||||
tippersStr = strings.Join(tippersSlice[:maxNamesInTipperMessage], " ")
|
||||
tippersStr = tippersStr + " ... and others"
|
||||
}
|
||||
return tippersStr
|
||||
}
|
||||
|
||||
// getTooltipMessage will return the full tip tool tip
|
||||
func (x Message) getTooltipMessage(botUserName string, notInitializedWallet bool) string {
|
||||
tippersStr := getTippersString(x.Tippers)
|
||||
tipToolTipMessage := fmt.Sprintf("🏅 %d sat", x.TipAmount)
|
||||
if len(x.Tippers) > 1 {
|
||||
tipToolTipMessage = fmt.Sprintf("%s (%d tips by %s)", tipToolTipMessage, x.Ntips, tippersStr)
|
||||
} else {
|
||||
tipToolTipMessage = fmt.Sprintf("%s (by %s)", tipToolTipMessage, tippersStr)
|
||||
}
|
||||
|
||||
if notInitializedWallet {
|
||||
tipToolTipMessage = tipToolTipMessage + fmt.Sprintf("\n🗑 Chat with %s to manage your wallet.", botUserName)
|
||||
}
|
||||
return tipToolTipMessage
|
||||
}
|
||||
|
||||
// tipTooltipExists checks if this tip is already known
|
||||
func tipTooltipExists(m *tb.Message, bot *TipBot) (bool, *Message) {
|
||||
for _, tip := range bot.tips[m.ReplyTo.Sender.ID] {
|
||||
if tip.Message.ReplyTo != nil && m.ReplyTo != nil {
|
||||
if tip.Message.ReplyTo.ID == m.ReplyTo.ID {
|
||||
return true, tip
|
||||
}
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// tipTooltipHandler function to update the tooltip below a tipped message. either updates or creates initial tip tool tip
|
||||
func tipTooltipHandler(m *tb.Message, user *tb.User, bot *TipBot, amount int, notInitializedWallet bool) bool {
|
||||
// todo: this crashes if the tooltip message (maybe also the original tipped message) was deleted in the mean time!!! need to check for existence!
|
||||
ok, tipMessage := tipTooltipExists(m, bot)
|
||||
if ok {
|
||||
// update the tooltip with new tippers
|
||||
tipMessage.updateTooltip(bot, user, amount, notInitializedWallet)
|
||||
} else {
|
||||
tipmsg := fmt.Sprintf("🏅 %d sat", amount)
|
||||
userStr := GetUserStrMd(user)
|
||||
tipmsg = fmt.Sprintf("%s (by %s)", tipmsg, userStr)
|
||||
|
||||
if notInitializedWallet {
|
||||
tipmsg = tipmsg + fmt.Sprintf("\n🗑 Chat with %s to manage your wallet.", GetUserStrMd(bot.telegram.Me))
|
||||
}
|
||||
msg, err := bot.telegram.Reply(m.ReplyTo, tipmsg, tb.Silent)
|
||||
if err != nil {
|
||||
print(err)
|
||||
}
|
||||
message := NewMessage(msg, TipAmount(amount), Tips(1))
|
||||
message.Tippers = appendUinqueUsersToSlice(message.Tippers, user)
|
||||
bot.tips[m.ReplyTo.Sender.ID] = append(bot.tips[m.ReplyTo.Sender.ID], message)
|
||||
}
|
||||
// first call will return false, every following call will return true
|
||||
return ok
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
tb "gopkg.in/tucnak/telebot.v2"
|
||||
@@ -95,13 +94,13 @@ func (bot *TipBot) GetUserBalance(user *tb.User) (amount int, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) error {
|
||||
user := &lnbits.User{Telegram: tbUser}
|
||||
func (bot *TipBot) CreateWalletForUser(tbUser *tb.User) error {
|
||||
user, err := GetUser(tbUser, *bot)
|
||||
userStr := GetUserStr(tbUser)
|
||||
log.Printf("[CreateWalletForTelegramUser] Creating wallet for user %s ... ", userStr)
|
||||
err := bot.createWallet(user)
|
||||
log.Printf("[CreateWalletForUser] Creating wallet for user %s ... ", userStr)
|
||||
err = bot.createWallet(user)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[CreateWalletForTelegramUser] Error: Could not create wallet for user %s", userStr)
|
||||
errmsg := fmt.Sprintf("[CreateWalletForUser] Error: Could not create wallet for user %s", userStr)
|
||||
log.Errorln(errmsg)
|
||||
return err
|
||||
}
|
||||
@@ -109,7 +108,7 @@ func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) error {
|
||||
if tx.Error != nil {
|
||||
return tx.Error
|
||||
}
|
||||
log.Printf("[CreateWalletForTelegramUser] Wallet created for user %s. ", userStr)
|
||||
log.Printf("[CreateWalletForUser] Wallet created for user %s. ", userStr)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user