-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathphoto.go
79 lines (73 loc) · 2.26 KB
/
photo.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
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."
photoQrRecognizedMessage = "✅ QR code:\n`%s`"
)
// TryRecognizeInvoiceFromQrCode will try to read an invoice string from a qr code and invoke the payment handler.
func TryRecognizeQrCode(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) || lightning.IsLnurl(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 := TryRecognizeQrCode(img)
if err != nil {
log.Errorf("tryRecognizeQrCodes error: %v\n", err)
bot.trySendMessage(m.Sender, photoQrNotRecognizedMessage)
return
}
bot.trySendMessage(m.Sender, fmt.Sprintf(photoQrRecognizedMessage, data.String()))
// invoke payment handler
if lightning.IsInvoice(data.String()) {
m.Text = fmt.Sprintf("/pay %s", data.String())
bot.confirmPaymentHandler(m)
return
} else if lightning.IsLnurl(data.String()) {
m.Text = fmt.Sprintf("/lnurl %s", data.String())
bot.lnurlHandler(m)
return
}
}