-
Notifications
You must be signed in to change notification settings - Fork 41
/
send.go
291 lines (261 loc) · 9.33 KB
/
send.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package main
import (
"fmt"
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/pkg/lightning"
log "github.com/sirupsen/logrus"
tb "gopkg.in/tucnak/telebot.v2"
)
const (
sendValidAmountMessage = "Did you enter a valid amount?"
sendUserNotFoundMessage = "User %s could not be found. You can /send only to Telegram tags like @%s."
sendIsNotAUsser = "🚫 %s is not a username. You can /send only to Telegram tags like @%s."
sendUserHasNoWalletMessage = "🚫 User %s hasn't created a wallet yet."
sendSentMessage = "💸 %d sat sent to %s."
sendReceivedMessage = "🏅 %s 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 ❤️`\n" +
"*Example:* `/send 1234 [email protected]`"
)
func helpSendUsage(errormsg string) string {
if len(errormsg) > 0 {
return fmt.Sprintf(sendHelpText, fmt.Sprintf("%s", errormsg))
} else {
return fmt.Sprintf(sendHelpText, "")
}
}
func (bot *TipBot) SendCheckSyntax(m *tb.Message) (bool, string) {
arguments := strings.Split(m.Text, " ")
if len(arguments) < 2 {
return false, fmt.Sprintf("Did you enter an amount and a recipient? You can use the /send command to either send to Telegram users like @%s or to a Lightning address like [email protected].", bot.telegram.Me.Username)
}
// if len(arguments) < 3 {
// return false, "Did you enter a recipient?"
// }
// if !strings.HasPrefix(arguments[0], "/send") {
// return false, "Did you enter a valid command?"
// }
return true, ""
}
// confirmPaymentHandler invoked on "/send 123 @user" command
func (bot *TipBot) confirmSendHandler(m *tb.Message) {
// reset state immediately
user, err := GetUser(m.Sender, *bot)
if err != nil {
return
}
ResetUserState(user, *bot)
// check and print all commands
bot.anyTextHandler(m)
// If the send is a reply, then trigger /tip handler
if m.IsReply() {
bot.tipHandler(m)
return
}
if ok, errstr := bot.SendCheckSyntax(m); !ok {
bot.trySendMessage(m.Sender, helpSendUsage(errstr))
NewMessage(m, WithDuration(0, bot.telegram))
return
}
// get send amount, returns 0 if no amount is given
amount, err := decodeAmountFromCommand(m.Text)
// info: /send 10 <user> DEMANDS an amount, while /send <[email protected]> also works without
// todo: /send <user> should also invoke amount input dialog if no amount is given
// CHECK whether first or second argument is a LIGHTNING ADDRESS
arg := ""
if len(strings.Split(m.Text, " ")) > 2 {
arg, err = getArgumentFromCommand(m.Text, 2)
} else if len(strings.Split(m.Text, " ")) == 2 {
arg, err = getArgumentFromCommand(m.Text, 1)
}
if err == nil {
if lightning.IsLightningAddress(arg) {
// if the second argument is a lightning address, then send to that address
err = bot.sendToLightningAddress(m, arg, amount)
if err != nil {
log.Errorln(err.Error())
return
}
return
}
}
// ASSUME INTERNAL SEND TO TELEGRAM USER
if err != nil || amount < 1 {
errmsg := fmt.Sprintf("[/send] Error: Send amount not valid.")
log.Errorln(errmsg)
// immediately delete if the amount is bullshit
NewMessage(m, WithDuration(0, bot.telegram))
bot.trySendMessage(m.Sender, helpSendUsage(sendValidAmountMessage))
return
}
// SEND COMMAND IS VALID
// check for memo in command
sendMemo := GetMemoFromCommand(m.Text, 3)
if len(m.Entities) < 2 {
arg, err := getArgumentFromCommand(m.Text, 2)
if err != nil {
log.Errorln(err.Error())
return
}
arg = MarkdownEscape(arg)
NewMessage(m, WithDuration(0, bot.telegram))
errmsg := fmt.Sprintf("Error: User %s could not be found", arg)
bot.trySendMessage(m.Sender, helpSendUsage(fmt.Sprintf(sendUserNotFoundMessage, arg, bot.telegram.Me.Username)))
log.Errorln(errmsg)
return
}
if m.Entities[1].Type != "mention" {
arg, err := getArgumentFromCommand(m.Text, 2)
if err != nil {
NewMessage(m, WithDuration(0, bot.telegram))
log.Errorln(err.Error())
return
}
arg = MarkdownEscape(arg)
NewMessage(m, WithDuration(0, bot.telegram))
errmsg := fmt.Sprintf("Error: %s is not a user", arg)
bot.trySendMessage(m.Sender, fmt.Sprintf(sendIsNotAUsser, arg, bot.telegram.Me.Username))
log.Errorln(errmsg)
return
}
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 = ?", strings.ToLower(toUserStrWithoutAt)).First(toUserDb)
if tx.Error != nil || toUserDb.Wallet == nil || toUserDb.Initialized == false {
NewMessage(m, WithDuration(0, bot.telegram))
err = fmt.Errorf(sendUserHasNoWalletMessage, MarkdownEscape(toUserStrMention))
bot.trySendMessage(m.Sender, err.Error())
if tx.Error != nil {
log.Printf("[/send] Error: %v %v", err, tx.Error)
return
}
log.Printf("[/send] Error: %v", err)
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, WithDuration(0, bot.telegram))
log.Printf("[/send] Error: %s\n", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprint(errorTryLaterMessage))
return
}
SetUserState(user, *bot, lnbits.UserStateConfirmSend, sendData)
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
}
ResetUserState(user, *bot)
// 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
ResetUserState(user, *bot)
// we can now get the wallets of both users
to := &tb.User{ID: toId, Username: toUserStrWithoutAt}
from := c.Sender
toUserStrMd := GetUserStrMd(to)
fromUserStrMd := GetUserStrMd(from)
toUserStr := GetUserStr(to)
fromUserStr := GetUserStr(from)
transactionMemo := fmt.Sprintf("Send from %s to %s (%d sat).", fromUserStr, toUserStr, amount)
t := NewTransaction(bot, from, to, amount, TransactionType("send"))
t.Memo = transactionMemo
success, err := t.Send()
if !success || err != nil {
// NewMessage(m, WithDuration(0, bot.telegram))
bot.trySendMessage(c.Sender, fmt.Sprintf(sendErrorMessage, err))
errmsg := fmt.Sprintf("[/send] Error: Transaction failed. %s", err)
log.Errorln(errmsg)
return
}
bot.trySendMessage(from, fmt.Sprintf(sendSentMessage, amount, toUserStrMd))
bot.trySendMessage(to, fmt.Sprintf(sendReceivedMessage, fromUserStrMd, amount))
// send memo if it was present
if len(sendMemo) > 0 {
bot.trySendMessage(to, fmt.Sprintf("✉️ %s", MarkdownEscape(sendMemo)))
}
return
}