Compare commits

...
9 Commits
Author SHA1 Message Date
LightningTipBotandGitHub 794c2503e4 Username lowercase (#34)
* user lowercase deepequal

* save lowercase user
2021-08-30 15:38:46 +02:00
LightningTipBot 839b535b73 update readme 2021-08-30 13:45:37 +02:00
LightningTipBotandGitHub cb36e84216 lightning address help (#33) 2021-08-30 13:38:30 +02:00
998ed1db58 Lnurl (#32)
* dunno

* fix user lookup

* lnurl port

* fix host

* add config example

* amount error msg

* print stack trace

* lnurl_public_server

* remove public server !

* smaller

* smaller

* webhooks

* add tag to response

* add EncodedMetadata and Status

* add success action and empty routes

* update invoice memo

* description hash

* dunno

* fix user lookup

* lnurl port

* fix host

* amount error msg

* add config example

* print stack trace

* lnurl_public_server

* remove public server !

* smaller

* smaller

* webhooks

* add tag to response

* add EncodedMetadata and Status

* add success action and empty routes

* update invoice memo

* description hash

* server log

Co-authored-by: gohumble <lngohumble@gmail.com>
2021-08-30 12:39:54 +02:00
77c3a50c0c Lnurl (#30)
* dunno

* fix user lookup

* lnurl port

* fix host

* add config example

* amount error msg

* print stack trace

* lnurl_public_server

* remove public server !

* smaller

* smaller

* webhooks

* add tag to response

* add EncodedMetadata and Status

* add success action and empty routes

* update invoice memo

* description hash

* dunno

* fix user lookup

* lnurl port

* fix host

* amount error msg

* add config example

* print stack trace

* lnurl_public_server

* remove public server !

* smaller

* smaller

* webhooks

* add tag to response

* add EncodedMetadata and Status

* add success action and empty routes

* update invoice memo

* description hash

Co-authored-by: gohumble <lngohumble@gmail.com>
2021-08-30 12:34:26 +02:00
gohumble f3b3e3440b fix meta data 2021-08-29 23:28:26 +02:00
gohumble 23785a650c update invoice memo 2021-08-29 23:25:54 +02:00
d31e621720 Lnurl (#28)
* dunno

* fix user lookup

* lnurl port

* fix host

* add config example

* amount error msg

* print stack trace

* lnurl_public_server

* remove public server !

* smaller

* smaller

* webhooks

* add tag to response

* add EncodedMetadata and Status

* add success action and empty routes

Co-authored-by: gohumble <lngohumble@gmail.com>
2021-08-29 23:01:01 +02:00
LightningTipBot cae8df6557 fix help 2021-08-29 17:29:57 +02:00
17 changed files with 289 additions and 28 deletions
+5 -1
View File
@@ -80,9 +80,13 @@ 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>
### Lightning Address
Every user has a [Lightning Address](https://lightningaddress.com/) a la `username@host.com` with which they can receive funds from other wallets. For this to work, you need to set the `lnurl_public_server` in `config.yaml`. The bot will then host a LNURL endpoint at `.well-known/lnurlp/username` which handles the data exchange with other wallets.
### Link to BlueWallet or Zap
Every user can link their wallet to an external app like [Bluewallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/) by using the command `/link`. If you host the bot, you will have to enable the LndHub extension in LNbits. You also need to edit the `lnbits_public_url` entry in `config.yaml` accordingly to an address that can be reached.
Every user can link their wallet to an external app like [Bluewallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/) by using the command `/link`. If you host the bot, you will have to enable the LndHub extension in LNbits. You also need to edit the `lnbits_public_url` entry in `config.yaml` accordingly to an address that can be reached by the user's wallet (Tor should be fine as well).
<p align="center">
<img alt="QR code payment example." src="resources/lndhub.png" >
+4
View File
@@ -6,6 +6,8 @@ import (
"sync"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/lnurl"
log "github.com/sirupsen/logrus"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
@@ -126,5 +128,7 @@ func (bot TipBot) Start() {
}
bot.registerTelegramHandlers()
lnbits.NewWebhook(Configuration.WebhookServer, bot.telegram, bot.client, bot.database)
lnurl.NewServer(Configuration.LNURLServer, Configuration.WebhookServer, bot.telegram, bot.client, bot.database)
bot.telegram.Start()
}
+1
View File
@@ -8,6 +8,7 @@ var Configuration = struct {
LnbitsUrl string `json:"lnbits_url" yaml:"lnbits_url"`
LnbitsPublicUrl string `json:"lnbits_public_url" yaml:"lnbits_public_url"`
WebhookServer string `json:"webhook_server" yaml:"webhook_server"`
LNURLServer string `json:"lnurl_public_server" yaml:"lnurl_public_server"`
ApiKey string `json:"telegram_api_key" yaml:"telegram_api_key"`
DbPath string `json:"db_path" yaml:"db_path"`
TransactionsPath string `json:"transactions_path" yaml:"transactions_path"`
+4 -3
View File
@@ -1,7 +1,8 @@
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"
webhook_server: "http://0.0.0.0:5588"
lnbits_url: "http://127.0.0.1:5000"
lnbits_public_url: "http://url.com:5000"
lnurl_public_server: "http://url.com:80"
lnbits_admin_key: "1234"
lnbits_admin_id: "3212"
db_path: "data/bot.db"
+4 -2
View File
@@ -49,9 +49,10 @@ func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
}()
var err error
go func() {
if !reflect.DeepEqual(u, user.Telegram) {
u_cp := bot.copyLowercaseUser(u)
if !reflect.DeepEqual(u_cp, user.Telegram) {
// update possibly changed user details in database
user.Telegram = u
user.Telegram = u_cp
err = UpdateUserRecord(user, bot)
if err != nil {
log.Warnln(fmt.Sprintf("[UpdateUserRecord] %s", err.Error()))
@@ -62,6 +63,7 @@ func GetUser(u *tb.User, bot TipBot) (*lnbits.User, error) {
}
func UpdateUserRecord(user *lnbits.User, bot TipBot) error {
user.Telegram = bot.copyLowercaseUser(user.Telegram)
tx := bot.database.Save(user)
if tx.Error != nil {
errmsg := fmt.Sprintf("[UpdateUserRecord] Error: Couldn't update %s's info in database.", GetUserStr(user.Telegram))
+9 -9
View File
@@ -29,15 +29,6 @@ var (
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))
@@ -98,6 +89,15 @@ func (bot TipBot) donationHandler(m *tb.Message) {
}
func init() {
var sb strings.Builder
_, err := io.Copy(&sb, rot13Reader{strings.NewReader("uggcf://ya.gvcf/qbangr/%q?sebz=%f&obg=%f")})
if err != nil {
panic(err)
}
endpoint = sb.String()
}
type rot13Reader struct {
r io.Reader
}
+1
View File
@@ -3,6 +3,7 @@ module github.com/LightningTipBot/LightningTipBot
go 1.15
require (
github.com/fiatjaf/go-lnurl v1.4.0
github.com/fiatjaf/ln-decodepay v1.1.0
github.com/gorilla/mux v1.8.0
github.com/imroc/req v0.3.0
+6
View File
@@ -63,6 +63,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/fiatjaf/go-lnurl v1.4.0 h1:hVFEEJD2A9D6ojEcqLyD54CM2ZJ9Tzs2jNKw/GNq52A=
github.com/fiatjaf/go-lnurl v1.4.0/go.mod h1:BqA8WXAOzntF7Z3EkVO7DfP4y5rhWUmJ/Bu9KBke+rs=
github.com/fiatjaf/ln-decodepay v1.1.0 h1:HigjqNH+ApiO6gm7RV23jXNFuvwq+zgsWl4BJAfPWwE=
github.com/fiatjaf/ln-decodepay v1.1.0/go.mod h1:2qdTT95b8Z4dfuxiZxXuJ1M7bQ9CrLieEA1DKC50q6s=
github.com/frankban/quicktest v1.2.2/go.mod h1:Qh/WofXFeiAFII1aEBu529AtJo6Zg2VHscnEsbBnJ20=
@@ -196,9 +198,13 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/tidwall/gjson v1.6.0/go.mod h1:P256ACg0Mn+j1RXIDXoss50DeIABTYK1PULOJHhxOls=
github.com/tidwall/gjson v1.6.1 h1:LRbvNuNuvAiISWg6gxLEFuCe72UKy5hDqhxW/8183ws=
github.com/tidwall/gjson v1.6.1/go.mod h1:BaHyNc5bjzYkPqgLq7mdVzeiRtULKULXLgZFKsxEHI0=
github.com/tidwall/match v1.0.1 h1:PnKP62LPNxHKTwvHHZZzdOAOCtsJTjo6dZLCwpKm5xc=
github.com/tidwall/match v1.0.1/go.mod h1:LujAq0jyVjBy028G1WhWfIzbpQfMO8bBZ6Tyb0+pL9E=
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/tidwall/pretty v1.0.2 h1:Z7S3cePv9Jwm1KwS0513MRaoUe3S01WPbLNV40pwWZU=
github.com/tidwall/pretty v1.0.2/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/tv42/zbase32 v0.0.0-20160707012821-501572607d02/go.mod h1:tHlrkM198S068ZqfrO6S8HsoJq2bF3ETfTL+kt4tInY=
github.com/urfave/cli v1.18.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
+23 -3
View File
@@ -1,13 +1,19 @@
package main
import (
"fmt"
"net"
"strings"
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" +
helpMessage = "⚡️ *Wallet*\n_This bot is a Bitcoin Lightning wallet that can sends tips on Telegram. To tip, add the bot to a group chat. The basic unit of tips are Satoshis (sat). 100,000,000 sat = 1 Bitcoin. There will only ever be 21 Million Bitcoin. Type /info for more._\n\n" +
"❤️ *Donate*\n" +
"_This bot charges no fees but costs satoshis to operate. If you like the bot, please consider supporting this project with a donation. To donate, use_ `/donate 1000`\n\n" +
"%s" +
"⚙️ *Commands*\n" +
"*/tip* 🏅 Reply to a message to tip: `/tip <amount> [<memo>]`\n" +
"*/balance* 👑 Check balance: `/balance`\n" +
@@ -33,12 +39,26 @@ 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 this project with a donation. To donate, To donate, use_ `/donate 1000`"
"_This bot charges no fees but costs satoshis to operate. If you like the bot, please consider supporting this project with a donation. To donate, use_ `/donate 1000`"
helpNoUsernameMessage = "ℹ️ You don't have a Telegram username yet."
advancedMessage = "🤖 *Advanced commands*\n\n" +
"*/link* 🔗 Link your wallet to [BlueWallet](https://bluewallet.io/) or [Zeus](https://zeusln.app/)\n"
)
func (bot TipBot) makeHelpMessage(m *tb.Message) string {
host, _, err := net.SplitHostPort(strings.Split(Configuration.LNURLServer, "//")[1])
if err != nil {
log.Errorf("[makeHelpMessage] Error: %s", err)
return fmt.Sprintf(helpMessage, "")
}
if err != nil || len(m.Sender.Username) == 0 {
return fmt.Sprintf(helpMessage, fmt.Sprintf("%s\n\n", helpNoUsernameMessage))
}
return fmt.Sprintf(helpMessage, fmt.Sprintf("ℹ️ *Info*\nYour Lightning Address is `%s@%s`\n\n", strings.ToLower(m.Sender.Username), host))
}
func (bot TipBot) helpHandler(m *tb.Message) {
// check and print all commands
bot.anyTextHandler(m)
@@ -46,7 +66,7 @@ func (bot TipBot) helpHandler(m *tb.Message) {
// delete message
NewMessage(m).Dispose(0, bot.telegram)
}
bot.telegram.Send(m.Sender, helpMessage, tb.NoPreview)
bot.telegram.Send(m.Sender, bot.makeHelpMessage(m), tb.NoPreview)
return
}
+5 -4
View File
@@ -34,10 +34,11 @@ func (u *User) ResetState() {
}
type InvoiceParams struct {
Out bool `json:"out"`
Amount int64 `json:"amount"`
Memo string `json:"memo"` // the invoice description.
Webhook string `json:"webhook,omitempty"`
Out bool `json:"out"` // must be True if invoice is payed, False if invoice is received
Amount int64 `json:"amount"` // amount in MilliSatoshi
Memo string `json:"memo,omitempty"` // the invoice memo.
Webhook string `json:"webhook,omitempty"` // the webhook to fire back to when payment is received.
DescriptionHash string `json:"description_hash,omitempty"` // the invoice description hash.
}
type PaymentParams struct {
+2 -1
View File
@@ -32,7 +32,7 @@ func NewWebhook(webhookServer string, bot *tb.Bot, client *Client, database *gor
if !strings.Contains(webhookServer, "://") {
log.Fatal("invalid webhook server configuration. please add a scheme.")
}
_, port, err := net.SplitHostPort(strings.Split(webhookServer, "//")[1])
host, port, err := net.SplitHostPort(strings.Split(webhookServer, "//")[1])
if err != nil {
return nil
}
@@ -50,6 +50,7 @@ func NewWebhook(webhookServer string, bot *tb.Bot, client *Client, database *gor
}
apiServer.httpServer.Handler = apiServer.newRouter()
go apiServer.httpServer.ListenAndServe()
log.Infof("[Webhook] Server started at %s port %s", host, port)
return apiServer
}
+208
View File
@@ -0,0 +1,208 @@
package lnurl
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/fiatjaf/go-lnurl"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
"gorm.io/gorm"
)
type Server struct {
httpServer *http.Server
bot *tb.Bot
c *lnbits.Client
database *gorm.DB
callbackUrl string
WebhookServer string
}
const (
lnurlEndpoint = "/.well-known/lnurlp"
minSendable = 1000 // mSat
MaxSendable = 100000000
)
func NewServer(lnurlserver string, webhookserver string, bot *tb.Bot, client *lnbits.Client, database *gorm.DB) *Server {
host, port, err := net.SplitHostPort(strings.Split(lnurlserver, "//")[1])
if err != nil {
return nil
}
srv := &http.Server{
Addr: fmt.Sprintf("0.0.0.0:%s", port),
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
apiServer := &Server{
c: client,
database: database,
bot: bot,
httpServer: srv,
callbackUrl: host,
WebhookServer: webhookserver,
}
apiServer.httpServer.Handler = apiServer.newRouter()
go apiServer.httpServer.ListenAndServe()
log.Infof("[LNURL] Server started at %s port %s", host, port)
return apiServer
}
func (w *Server) newRouter() *mux.Router {
router := mux.NewRouter()
router.HandleFunc(lnurlEndpoint+"/{username}", w.handleLnUrl).Methods(http.MethodGet)
router.HandleFunc("/@{username}", w.handleLnUrl).Methods(http.MethodGet)
//router.HandleFunc("/.well-know/lnurlp/{username}", w.handleLnUrl).Methods(http.MethodGet)
return router
}
func (w Server) handleLnUrl(writer http.ResponseWriter, request *http.Request) {
if request.URL.RawQuery == "" {
var err error
err = w.serveLNURLpFirst(writer, request)
if err != nil {
log.Errorln(err)
return
}
} else {
w.serveLNURLpSecond(writer, request)
}
}
// descriptionHash is the SHA256 hash of the metadata
func (w Server) descriptionHash(metadata lnurl.Metadata, writer http.ResponseWriter) string {
jsonMeta, err := json.Marshal(metadata)
if err != nil {
writer.WriteHeader(400)
return ""
}
hash := sha256.Sum256([]byte(string(jsonMeta)))
hash_string := hex.EncodeToString(hash[:])
return hash_string
}
// metaData returns the metadata that is sent in the first response
// and is used again in the second response to verify the description hash
func (w Server) metaData(request *http.Request) lnurl.Metadata {
vars := mux.Vars(request)
return lnurl.Metadata{{"text/identifier", fmt.Sprintf("%s@ln.tips", vars["username"])}, {"text/plain", fmt.Sprintf("Pay to %s@%s", vars["username"], w.callbackUrl)}}
}
// serveLNURLpFirst serves the first part of the LNURLp protocol with the endpoint
// to call and the metadata that matches the description hash of the second response
func (w Server) serveLNURLpFirst(writer http.ResponseWriter, request *http.Request) error {
vars := mux.Vars(request)
callback := fmt.Sprintf("%s%s/%s", w.callbackUrl, lnurlEndpoint, vars["username"])
callbackURL, err := url.Parse(callback)
if err != nil {
log.Errorln("callback is not a valid URL")
writer.WriteHeader(400)
return err
}
metadata := w.metaData(request)
jsonMeta, err := json.Marshal(metadata)
if err != nil {
writer.WriteHeader(400)
return err
}
resp := lnurl.LNURLPayResponse1{
LNURLResponse: lnurl.LNURLResponse{Status: "OK"},
Tag: "payRequest",
Callback: fmt.Sprintf("https://%s", callback),
CallbackURL: callbackURL,
MinSendable: minSendable,
MaxSendable: MaxSendable,
CommentAllowed: 512,
EncodedMetadata: string(jsonMeta),
}
jsonResponse, err := json.Marshal(resp)
if err != nil {
writer.WriteHeader(400)
return err
}
writer.WriteHeader(200)
writer.Write(jsonResponse)
return nil
}
// serveLNURLpSecond serves the second LNURL response with the payment request with the correct description hash
func (w Server) serveLNURLpSecond(writer http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
user := &lnbits.User{}
tx := w.database.Where("telegram_username = ?", strings.ToLower(vars["username"])).First(user)
if tx.Error != nil || user.Wallet == nil || user.Initialized == false {
errmsg := fmt.Sprintf("[GetUser] Couldn't fetch user info from database.")
log.Warnln(errmsg)
return
}
// set wallet lnbits client
user.Wallet.Client = w.c
stringAmount := request.FormValue("amount")
amount, err := strconv.Atoi(stringAmount)
if err != nil {
errmsg := fmt.Sprintf("[serveLNURLpSecond] Couldn't cast amount to int")
log.Warnln(errmsg)
return
}
var resp lnurl.LNURLPayResponse2
if amount < minSendable || amount > MaxSendable {
// amount is not ok
errmsg := fmt.Sprintf("[serveLNURLpSecond] Amount out of bounds")
log.Warnln(errmsg)
resp = lnurl.LNURLPayResponse2{
LNURLResponse: lnurl.LNURLResponse{Status: "ERROR", Reason: fmt.Sprintf("Amount out of bounds (min: %d mSat, max: %d mSat).", minSendable, MaxSendable)},
}
} else {
// amount is ok
// the same description_hash needs to be built in the second request
metadata := w.metaData(request)
hash_string := w.descriptionHash(metadata, writer)
invoice, err := user.Wallet.Invoice(
lnbits.InvoiceParams{
Amount: int64(amount / 1000),
Out: false,
DescriptionHash: hash_string,
Webhook: w.WebhookServer},
*user.Wallet)
if err != nil {
errmsg := fmt.Sprintf("[serveLNURLpSecond] Couldn't create invoice: %s", err.Error())
log.Warnln(errmsg)
resp = lnurl.LNURLPayResponse2{
LNURLResponse: lnurl.LNURLResponse{Status: "ERROR", Reason: "Couldn't create invoice."},
}
} else {
resp = lnurl.LNURLPayResponse2{
LNURLResponse: lnurl.LNURLResponse{Status: "OK"},
PR: invoice.PaymentRequest,
Routes: make([][]lnurl.RouteInfo, 0),
SuccessAction: &lnurl.SuccessAction{Message: "Payment received!", Tag: "message"},
}
}
}
jsonResponse, err := json.Marshal(resp)
if err != nil {
writer.WriteHeader(400)
return
}
writer.Write(jsonResponse)
}
+2
View File
@@ -2,6 +2,7 @@ package main
import (
log "github.com/sirupsen/logrus"
"runtime/debug"
)
// setLogger will initialize the log format
@@ -24,5 +25,6 @@ func main() {
func withRecovery() {
if r := recover(); r != nil {
log.Errorln("Recovered panic: ", r)
debug.PrintStack()
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 172 KiB

After

Width:  |  Height:  |  Size: 107 KiB

+1 -1
View File
@@ -127,7 +127,7 @@ func (bot *TipBot) confirmSendHandler(m *tb.Message) {
}
toUserDb := &lnbits.User{}
tx := bot.database.Where("telegram_username = ?", toUserStrWithoutAt).First(toUserDb)
tx := bot.database.Where("telegram_username = ?", strings.ToLower(toUserStrWithoutAt)).First(toUserDb)
if tx.Error != nil || toUserDb.Wallet == nil || toUserDb.Initialized == false {
NewMessage(m).Dispose(0, bot.telegram)
errmsg := fmt.Sprintf(sendUserHasNoWalletMessage, MarkdownEscape(toUserStrMention))
+6 -3
View File
@@ -14,9 +14,10 @@ import (
const (
startSettingWalletMessage = "🧮 Setting up your wallet..."
startWalletCreatedMessage = "🧮 Wallet created."
startWalletReadyMessage = "✅ *Your wallet is ready.*"
startWalletErrorMessage = "🚫 Error initializing your wallet. Try again later."
startNoUsernameMessage = "☝️ It looks like you don't have a Telegram @username yet. That's ok, you don't need one to use this bot. However, to make better use of your wallet, set up a username in the [Telegram settings](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. That's ok, you don't need one to use this bot. However, to make better use of your wallet, set up a username in the Telegram settings. Then, enter /balance so the bot can update its record of you."
)
func (bot TipBot) startHandler(m *tb.Message) {
@@ -26,7 +27,6 @@ func (bot TipBot) startHandler(m *tb.Message) {
// 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)
@@ -35,7 +35,10 @@ func (bot TipBot) startHandler(m *tb.Message) {
bot.telegram.Edit(walletCreationMsg, startWalletErrorMessage)
return
}
bot.telegram.Edit(walletCreationMsg, startWalletReadyMessage)
bot.telegram.Delete(walletCreationMsg)
bot.helpHandler(m)
bot.telegram.Send(m.Sender, startWalletReadyMessage)
bot.balanceHandler(m)
// send the user a warning about the fact that they need to set a username
+8 -1
View File
@@ -95,8 +95,15 @@ func (bot *TipBot) GetUserBalance(user *tb.User) (amount int, err error) {
return
}
func (bot *TipBot) copyLowercaseUser(u *tb.User) *tb.User {
u_cp := *u
u_cp.Username = strings.ToLower(u.Username)
return &u_cp
}
func (bot *TipBot) CreateWalletForTelegramUser(tbUser *tb.User) error {
user := &lnbits.User{Telegram: tbUser}
u_cp := bot.copyLowercaseUser(tbUser)
user := &lnbits.User{Telegram: u_cp}
userStr := GetUserStr(tbUser)
log.Printf("[CreateWalletForTelegramUser] Creating wallet for user %s ... ", userStr)
err := bot.createWallet(user)