-
Notifications
You must be signed in to change notification settings - Fork 13
/
bot.go
972 lines (851 loc) · 28.6 KB
/
bot.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
package monerotipbot
import (
"encoding/json"
"errors"
"fmt"
"image"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/fsnotify/fsnotify"
"github.com/gabstv/httpdigest"
"github.com/makiuchi-d/gozxing"
"github.com/makiuchi-d/gozxing/qrcode"
"github.com/monero-ecosystem/go-monero-rpc-client/wallet"
zmq "github.com/pebbe/zmq4"
"github.com/spf13/viper"
statsd "github.com/smira/go-statsd"
tgbotapi "gopkg.in/telegram-bot-api.v4"
)
// MoneroTipBot is out Monero Tip Bot
type MoneroTipBot struct {
walletrpc wallet.Client
bot *tgbotapi.BotAPI
message *tgbotapi.Message
callback *tgbotapi.CallbackQuery
from *tgbotapi.User
giveaways []*Giveaway
qrcodes []*QRCode
rpcchannel *zmq.Socket
statsdclient *statsd.Client
}
var usernameregexp *regexp.Regexp
var mutex sync.RWMutex
// NewBot creates a new monerotipbot instance
func NewBot(conf *Config) (*MoneroTipBot, error) {
configpath := conf.GetConfig()
if configpath == "" {
configpath = filepath.Join(os.Getenv("HOME"), "settings.toml")
}
// parse the monerotipbot config file
viper.SetConfigType("yaml")
viper.SetConfigName(strings.TrimSuffix(path.Base(configpath), path.Ext(configpath)))
viper.AddConfigPath(path.Dir(configpath))
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config file changed:", e.Name)
})
err := viper.ReadInConfig()
if err != nil {
return nil, err
}
bot, err := tgbotapi.NewBotAPI(viper.GetString("telegram_bot_token"))
if err != nil {
return nil, err
}
if conf.GetDebug() {
log.Printf("Authorized on account %s", bot.Self.UserName)
bot.Debug = true
}
// this is a regexp matcher for Telegram users
usernameregexp, err = regexp.Compile("^(?i)[@]?[Aa-zZ]+\\w{4,}")
if err != nil {
return nil, err
}
// check if giveaway file exists, if not create it and load file
var giveaways []*Giveaway
giveawayfilename := viper.GetString("GIVEAWAY_FILE")
file, err := ioutil.ReadFile(giveawayfilename)
if err == nil {
err = json.Unmarshal(file, &giveaways)
if err != nil {
return nil, err
}
}
self := &MoneroTipBot{
bot: bot,
giveaways: giveaways,
// start a wallet client instance with login if login specified in settings
walletrpc: wallet.New(wallet.Config{
Address: viper.GetString("monero_rpc_daemon_url"),
Transport: httpdigest.New(viper.GetString("monero_rpc_daemon_username"), viper.GetString("monero_rpc_daemon_password")),
}),
}
if viper.GetBool("USE_STATSD") {
// initiate statsd client
self.statsdclient = statsd.NewClient(viper.GetString("statsd_address"), statsd.MetricPrefix(viper.GetString("statsd_prefix")), statsd.SendLoopCount(10), statsd.MaxPacketSize(100000))
}
// initiate zmq channel for rpc calls to this bot (for now only for broadcasting messages to users)
responder, _ := zmq.NewSocket(zmq.REP)
responder.Bind(viper.GetString("rpcchannel_uri"))
self.rpcchannel = responder
return self, nil
}
// Run starts the bot in a loop
func (mtb *MoneroTipBot) Run() error {
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := mtb.bot.GetUpdatesChan(u)
if err != nil {
return err
}
// track in how many groups this bot is actually used in.
// in your code editor, search the above comment (whole line) to see what I do with the groupsBotIsIn variable.
groupsBotIsIn := make(map[int64]*tgbotapi.Chat)
go groupTrackerLogger(groupsBotIsIn)
// listen on the ZMQ socket for notifications
go mtb.listenRPC()
defer mtb.rpcchannel.Close()
for update := range updates {
if update.Message != nil {
// log the event of the bot joining a group
if update.Message.NewChatMembers != nil {
for _, member := range *update.Message.NewChatMembers {
if member.UserName == viper.GetString("BOT_NAME") && member.IsBot {
mtb.statsdIncr("bot_group_join.counter", 1)
}
}
}
// log the event of the bot leaving (being kicked out of) a group
if update.Message.LeftChatMember != nil {
if update.Message.LeftChatMember.UserName == viper.GetString("BOT_NAME") && update.Message.LeftChatMember.IsBot {
mtb.statsdIncr("bot_group_left.counter", 1)
}
}
// track in how many groups this bot is actually used in
if update.Message.Chat != nil {
mutex.Lock()
groupsBotIsIn[update.Message.Chat.ID] = update.Message.Chat
mutex.Unlock()
}
// bots are not allowed to talk to us.
if update.Message.From.IsBot {
continue
}
// generally assume all update events to be message events
mtb.message = update.Message
mtb.from = update.Message.From
}
// now filter further: check if this is a message or a callback
iscallback := false
if update.CallbackQuery != nil {
// bots are not allowed to talk to us.
// notice: we check on the FROM object, not the Message object!
// on a callback the Message object will always be from the bot!
if update.CallbackQuery.From.IsBot {
continue
}
iscallback = true
mtb.callback = update.CallbackQuery
mtb.from = update.CallbackQuery.From
// trick: we pass the message referenced in the callback to our message type
mtb.message = update.CallbackQuery.Message
}
if mtb.from == nil {
mtb.destroy()
continue
}
if !iscallback {
if mtb.message.IsCommand() {
// ignore commands from forwarded messages
if mtb.message.ForwardFrom != nil || mtb.message.ForwardFromChat != nil {
mtb.destroy()
continue
}
// request pre-checks
err := mtb.requestPreCheck()
if err != nil {
mtb.destroy()
continue
}
err = mtb.parseCommand()
if err != nil {
mtb.destroy()
continue
}
} else {
// check if we received a photo (possibly a qr-code)
if mtb.message.Photo != nil {
err = mtb.parsePhoto()
if err != nil {
mtb.destroy()
continue
}
}
}
}
// not a command? then handle callbackqueries here
if mtb.callback != nil {
// request pre-checks
err := mtb.requestPreCheck()
if err != nil {
mtb.destroy()
continue
}
if strings.HasPrefix(mtb.callback.Data, "giveaway_") {
err = mtb.processGiveaway()
if err != nil {
mtb.destroy()
continue
}
}
if strings.HasPrefix(mtb.callback.Data, "qrcode_") {
err = mtb.processQRCode()
if err != nil {
mtb.destroy()
continue
}
}
}
/*
********************************************
IMPORTANT!!! DESTROY UPDATE REFERENCES HERE!
********************************************
*/
mtb.destroy()
}
return nil
}
func (mtb *MoneroTipBot) destroy() {
mtb.message = nil
mtb.callback = nil
mtb.from = nil
// save the wallet (IMPORTANT!)
mtb.walletrpc.Store()
// // destroy ZMQ socket
// mtb.rpcchannel.Close()
// // destroy statsdclient
// mtb.statsdclient.Close()
}
func (mtb *MoneroTipBot) hasUserNameHandle() bool {
if len(mtb.from.UserName) == 0 {
reply := &Message{
Format: true,
ChatID: mtb.getReplyID(),
}
if mtb.message.Chat.IsPrivate() {
reply.Text = "You have no username set. Please set a username handle in your Telegram settings to be able to interact with this bot. Type in /start again if you are ready."
} else {
reply.Text = "You have no username set. Please set a username handle in your Telegram settings to be able to interact with this bot."
}
mtb.reply(reply)
return false
}
return true
}
func (mtb *MoneroTipBot) reply(msg *Message) error {
botmsg := tgbotapi.NewMessage(msg.ChatID, "")
if msg.Format {
botmsg.ParseMode = "Markdown"
botmsg.Text = fmt.Sprintf("```\n%s```", msg.Text)
} else {
botmsg.ParseMode = "HTML"
botmsg.Text = fmt.Sprintf("%s", msg.Text)
}
_, err := mtb.bot.Send(botmsg)
mtb.statsdIncr("botreplymessages.counter", 1)
return err
}
func (mtb *MoneroTipBot) requestPreCheck() error {
if !mtb.hasUserNameHandle() {
return errors.New("No username handle")
}
msg := mtb.newReplyMessage(false)
// get user's wallet account
useraccount, err := mtb.getUserAccount()
if err != nil {
msg.Text = fmt.Sprintf("Error: %s", err)
mtb.reply(msg)
return err
}
if useraccount == nil {
err := mtb.createAccountIfNotExists()
if err != nil {
return err
}
}
return nil
}
func (mtb *MoneroTipBot) createAccountIfNotExists() error {
msg := mtb.newReplyMessage(true)
// get user's wallet account
useraccount, err := mtb.getUserAccount()
if err != nil {
return err
}
if useraccount != nil {
msg.Text = fmt.Sprintf("Account completed. Welcome %s", mtb.getUsername())
mtb.reply(msg)
return err
}
return mtb.createAccount()
}
func (mtb *MoneroTipBot) createAccount() error {
resp, err := mtb.walletrpc.CreateAccount(&wallet.RequestCreateAccount{
Label: fmt.Sprintf("%s@%d", strings.ToLower(mtb.getUsername()), mtb.getUsernameID()),
})
if err != nil {
mtb.reply(&Message{
Text: fmt.Sprintf("Error while creating account: %s", err),
Format: true,
ChatID: mtb.getUsernameID(),
})
return err
}
// stat account creation
mtb.statsdIncr("account_created.counter", 1)
if mtb.message.Chat.IsPrivate() {
msg := &Message{
Format: true,
ChatID: mtb.getReplyID(),
}
msg.Text = fmt.Sprintf("Address has been created for user: %s", mtb.getUsername())
mtb.reply(msg)
msg.Text = fmt.Sprintf("Please deposit the amount you wish to your newly created address: %s", resp.Address)
mtb.reply(msg)
msg.Text = fmt.Sprintf("This address is dedicated to your user only. Only the user with user id #%d (which is you) can control it. Telegram assigns a new user ID for new accounts. So make sure you withdraw all your funds, should you ever decide to delete your telegram account.", mtb.getUsernameID())
mtb.reply(msg)
}
return nil
}
func (mtb *MoneroTipBot) parseCommand() error {
// let's do our filtering of group and PM commands in this section.
// basically, everything is a PM command, except GIVEAWAY and TIP.
// filter accordingly.
msg := mtb.newReplyMessage(true)
msg.Text = "This command is only available in the bot PM. Please don't spam the group."
switch mtb.message.Command() {
case COMMANDS[START]:
if !mtb.message.Chat.IsPrivate() {
return mtb.reply(msg)
}
// stat this command invocation
mtb.statsdIncr("commands.START.counter", 1)
return mtb.parseCommandSTART()
case COMMANDS[HELP]:
if !mtb.message.Chat.IsPrivate() {
return mtb.reply(msg)
}
// stat this command invocation
mtb.statsdIncr("commands.HELP.counter", 1)
return mtb.parseCommandHELP()
case COMMANDS[TIP]:
// stat this command invocation
mtb.statsdIncr("commands.TIP.counter", 1)
return mtb.parseCommandTIP()
case COMMANDS[SEND]:
if !mtb.message.Chat.IsPrivate() {
return mtb.reply(msg)
}
// stat this command invocation
mtb.statsdIncr("commands.SEND.counter", 1)
return mtb.parseCommandSEND()
case COMMANDS[GIVEAWAY]:
// stat this command invocation
mtb.statsdIncr("commands.GIVEAWAY.counter", 1)
return mtb.parseCommandGIVEAWAY()
case COMMANDS[WITHDRAW]:
if !mtb.message.Chat.IsPrivate() {
return mtb.reply(msg)
}
// stat this command invocation
mtb.statsdIncr("commands.WITHDRAW.counter", 1)
return mtb.parseCommandWITHDRAW()
case COMMANDS[BALANCE]:
if !mtb.message.Chat.IsPrivate() {
return mtb.reply(msg)
}
// stat this command invocation
mtb.statsdIncr("commands.BALANCE.counter", 1)
return mtb.parseCommandBALANCE()
case COMMANDS[GENERATEQR]:
if !mtb.message.Chat.IsPrivate() {
return mtb.reply(msg)
}
// stat this command invocation
mtb.statsdIncr("commands.GENERATEQR.counter", 1)
return mtb.parseCommandGENERATEQR()
}
return nil
}
func (mtb *MoneroTipBot) getUserAccount() (*Account, error) {
msg := mtb.newReplyMessage(true)
accounts, err := mtb.walletrpc.GetAccounts(&wallet.RequestGetAccounts{})
if err != nil {
msg.Text = fmt.Sprintf("Error while retrieving accounts: %s", err)
mtb.reply(msg)
return nil, err
}
// stat this command invocation
mtb.statsdGauge("user_accounts.counter", int64(len(accounts.SubaddressAccounts)))
// stat the total balance
mtb.statsdFGauge("total_balance.counter", wallet.XMRToFloat64(accounts.TotalBalance))
mtb.statsdFGauge("total_unlocked_balance.counter", wallet.XMRToFloat64(accounts.TotalUnlockedBalance))
for _, address := range accounts.SubaddressAccounts {
// stat labels so we have them stored somewhere else than only in local files
split := strings.Split(address.Label, "@")
if len(split) == 2 {
userid, err := strconv.ParseInt(split[1], 10, 64)
if err == nil {
mtb.statsdGauge(fmt.Sprintf("account_labels_usernames.%s", split[0]), userid)
mtb.statsdGauge(fmt.Sprintf("account_labels.%d", userid), int64(address.AccountIndex))
mtb.statsdFGauge(fmt.Sprintf("account_balance_per_label.%d", userid), wallet.XMRToFloat64(address.Balance))
}
}
// IMPORTANT: we need to check for both, username AND userid. one after the other.
// a user could change his username. but userid is still the same!
// first we try with the username.
label := fmt.Sprintf("%s@", strings.ToLower(mtb.getUsername()))
if strings.Contains(address.Label, label) {
useraccount := &Account{
AccountIndex: address.AccountIndex,
Balance: address.Balance,
BaseAddress: address.BaseAddress,
Label: address.Label,
Tag: address.Tag,
UnlockedBalance: address.UnlockedBalance,
}
// label the account of a known user on every request. this is a cheap operation
if mtb.isKnownUser() {
mtb.walletrpc.LabelAccount(&wallet.RequestLabelAccount{
AccountIndex: address.AccountIndex,
Label: fmt.Sprintf("%s@%d", strings.ToLower(mtb.getUsername()), mtb.getUsernameID()),
})
}
return useraccount, nil
}
// continue with next, if userid is 0.
if mtb.getUsernameID() == 0 {
continue
}
// username not found. maybe the user changed his username. so check for the userid.
label = fmt.Sprintf("@%d", mtb.getUsernameID())
if strings.Contains(address.Label, label) {
useraccount := &Account{
AccountIndex: address.AccountIndex,
Balance: address.Balance,
BaseAddress: address.BaseAddress,
Label: address.Label,
Tag: address.Tag,
UnlockedBalance: address.UnlockedBalance,
}
// label the account of a known user on every request. this is a cheap operation
if mtb.isKnownUser() {
mtb.walletrpc.LabelAccount(&wallet.RequestLabelAccount{
AccountIndex: address.AccountIndex,
Label: fmt.Sprintf("%s@%d", strings.ToLower(mtb.getUsername()), mtb.getUsernameID()),
})
}
return useraccount, nil
}
}
return nil, nil
}
func (mtb *MoneroTipBot) getReplyID() int64 {
if mtb.isKnownUser() {
return int64(mtb.from.ID)
}
return mtb.message.Chat.ID
}
func (mtb *MoneroTipBot) getUsernameID() int64 {
if mtb.isKnownUser() {
return int64(mtb.from.ID)
}
return int64(mtb.message.From.ID)
}
func (mtb *MoneroTipBot) getUsername() string {
return mtb.from.UserName
}
func (mtb *MoneroTipBot) isReplyToMessage() bool {
if mtb.message.ReplyToMessage != nil {
mtb.statsdIncr("isreplytomessage.counter", 1)
return true
}
return false
}
func (mtb *MoneroTipBot) newReplyMessage(format bool) *Message {
return &Message{
Format: format,
ChatID: mtb.getReplyID(),
}
}
func (mtb *MoneroTipBot) isKnownUser() bool {
if mtb.from.ID != 0 {
return true
}
return false
}
func (mtb *MoneroTipBot) processGiveaway() error {
switch mtb.callback.Data {
case "giveaway_claim":
claimer := mtb.callback.From.UserName
for i, giveaway := range mtb.giveaways {
if giveaway.Message.MessageID == mtb.message.MessageID {
if giveaway.From.From.UserName == mtb.callback.From.UserName {
mtb.bot.AnswerCallbackQuery(tgbotapi.CallbackConfig{
CallbackQueryID: mtb.callback.ID,
Text: "Can't claim your own giveaway.",
})
return errors.New("Claimer is giver")
}
claimeraccount, err := mtb.getUserAccount()
if err != nil {
return err
}
var destinations []*wallet.Destination
destinations = append(destinations, &wallet.Destination{
Amount: giveaway.Amount,
Address: claimeraccount.BaseAddress,
})
// stat the transfer time
start := time.Now()
resp, err := mtb.walletrpc.Transfer(&wallet.RequestTransfer{
AccountIndex: giveaway.Sender.AccountIndex,
Destinations: destinations,
})
if err != nil {
edit := tgbotapi.NewEditMessageText(int64(mtb.callback.Message.Chat.ID), giveaway.Message.MessageID, fmt.Sprintf("User @%s is giving %f XMR away.\n\n...<b>%s</b>", giveaway.From.From.UserName, wallet.XMRToFloat64(giveaway.Amount), err))
edit.ParseMode = "HTML"
mtb.bot.Send(edit)
return err
}
mtb.statsdPrecisionTiming("transaction.time_to_complete", time.Since(start))
// stat the transaction count
mtb.statsdIncr("transactions.counter", 1)
mtb.giveaways = append(mtb.giveaways[:i], mtb.giveaways[i+1:]...)
mtb.saveGiveawayToFile()
tippermsg := mtb.newReplyMessage(false)
// replace the chatID with the giver. else we notify the taker.
tippermsg.ChatID = int64(giveaway.From.From.ID)
tippermsg.Text = fmt.Sprintf("You successfully tipped user @%s.", strings.TrimPrefix(claimer, "@"))
tippermsg.Text = fmt.Sprintf("%s\n\nAmount: %s\nFee: %s\nTxHash: <a href='%s%s'>%s</a>", tippermsg.Text, wallet.XMRToDecimal(resp.Amount), wallet.XMRToDecimal(resp.Fee), viper.GetString("blockexplorer_url"), resp.TxHash, resp.TxHash)
if giveaway.From.From.ID != 0 {
edit := tgbotapi.NewEditMessageText(int64(mtb.callback.Message.Chat.ID), giveaway.Message.MessageID, fmt.Sprintf("User @%s is giving %f XMR away.\n\n%f XMR given from @%s to @%s.", giveaway.From.From.UserName, wallet.XMRToFloat64(giveaway.Amount), wallet.XMRToFloat64(giveaway.Amount), giveaway.From.From.UserName, claimer))
mtb.bot.Send(edit)
msg := mtb.newReplyMessage(false)
msg.Text = fmt.Sprintf("You have been tipped with %f XMR from user @%s", wallet.XMRToFloat64(giveaway.Amount), giveaway.From.From.UserName)
err := mtb.reply(msg)
if err != nil {
edit := tgbotapi.NewEditMessageText(int64(mtb.callback.Message.Chat.ID), giveaway.Message.MessageID, fmt.Sprintf("User @%s is giving %f XMR away.\n\n%f XMR given from @%s to @%s.\n\n@%s, you have been tipped.", giveaway.From.From.UserName, wallet.XMRToFloat64(resp.Amount), wallet.XMRToFloat64(resp.Amount), giveaway.From.From.UserName, claimer, claimer))
mtb.bot.Send(edit)
// send notification to giver here
return mtb.reply(tippermsg)
}
// send notification to giver here. with user has been notified
tippermsg.Text = fmt.Sprintf("%s\n\nUser has been notified.", tippermsg.Text)
return mtb.reply(tippermsg)
}
edit := tgbotapi.NewEditMessageText(int64(mtb.callback.Message.Chat.ID), giveaway.Message.MessageID, fmt.Sprintf("User @%s is giving %f XMR away.\n\n%f XMR given from @%s to @%s.\n\n@%s, you have been tipped.\nPlease PM me (@%s) and click the 'Start' button to complete your account.", giveaway.From.From.UserName, wallet.XMRToFloat64(resp.Amount), wallet.XMRToFloat64(resp.Amount), giveaway.From.From.UserName, claimer, claimer, viper.GetString("BOT_NAME")))
edit.ParseMode = "HTML"
mtb.bot.Send(edit)
// final send because giveaway.From.From.ID was 0.
return mtb.reply(tippermsg)
}
}
case "giveaway_cancel":
if mtb.giveaways == nil {
return nil
}
for i, giveaway := range mtb.giveaways {
if giveaway.Message.MessageID == mtb.message.MessageID {
if giveaway.From.From.UserName == mtb.callback.From.UserName {
edit := tgbotapi.NewEditMessageText(int64(mtb.message.Chat.ID), giveaway.Message.MessageID, fmt.Sprintf("User @%s is giving %f XMR away\n\n...<b>Canceled!</b>", giveaway.From.From.UserName, wallet.XMRToFloat64(giveaway.Amount)))
edit.ParseMode = "HTML"
mtb.bot.Send(edit)
mtb.giveaways = append(mtb.giveaways[:i], mtb.giveaways[i+1:]...)
mtb.saveGiveawayToFile()
return nil
}
mtb.bot.AnswerCallbackQuery(tgbotapi.CallbackConfig{
CallbackQueryID: mtb.callback.ID,
Text: "Not your giveaway.",
})
return nil
}
}
default:
return errors.New("Could not parse CallbackQuery")
}
return nil
}
func (mtb *MoneroTipBot) processQRCode() error {
switch mtb.callback.Data {
case "qrcode_tx_send":
if mtb.qrcodes == nil {
return nil
}
msg := mtb.newReplyMessage(true)
for i, qrcode := range mtb.qrcodes {
if qrcode.Message.MessageID == mtb.message.MessageID {
if qrcode.From.From.UserName == mtb.callback.From.UserName {
useraccount, err := mtb.getUserAccount()
var destinations []*wallet.Destination
destinations = append(destinations, &wallet.Destination{
Amount: qrcode.Amount,
Address: qrcode.ParseURI.URI.Address,
})
// stat the transfer time
start := time.Now()
resp, err := mtb.walletrpc.Transfer(&wallet.RequestTransfer{
AccountIndex: useraccount.AccountIndex,
Destinations: destinations,
})
if err != nil {
edit := tgbotapi.NewEditMessageText(int64(mtb.callback.Message.Chat.ID), mtb.callback.Message.MessageID, fmt.Sprintf("%s\n\n...<b>%s! Aborted.</b>", mtb.callback.Message.Text, err))
edit.ParseMode = "HTML"
mtb.bot.Send(edit)
return err
}
mtb.statsdPrecisionTiming("transaction.time_to_complete", time.Since(start))
// stat the transaction count
mtb.statsdIncr("transactions.counter", 1)
edit := tgbotapi.NewEditMessageText(int64(mtb.callback.Message.Chat.ID), mtb.callback.Message.MessageID, fmt.Sprintf("%s\n\n...<b>Transaction complete!</b>", mtb.callback.Message.Text))
edit.ParseMode = "HTML"
mtb.bot.Send(edit)
msg.Format = false
msg.Text = fmt.Sprintf("Amount: %s\nFee: %s\nTxHash: <a href='%s%s'>%s", wallet.XMRToDecimal(resp.Amount), wallet.XMRToDecimal(resp.Fee), viper.GetString("blockexplorer_url"), resp.TxHash, resp.TxHash)
mtb.reply(msg)
mtb.qrcodes = append(mtb.qrcodes[:i], mtb.qrcodes[i+1:]...)
return nil
}
}
}
case "qrcode_tx_cancel":
if mtb.qrcodes == nil {
return nil
}
for i, qrcode := range mtb.qrcodes {
if qrcode.Message.MessageID == mtb.message.MessageID {
if qrcode.From.From.UserName == mtb.callback.From.UserName {
edit := tgbotapi.NewEditMessageText(int64(mtb.callback.Message.Chat.ID), mtb.callback.Message.MessageID, fmt.Sprintf("%s\n\n...<b>Canceled!</b>", mtb.callback.Message.Text))
edit.ParseMode = "HTML"
mtb.bot.Send(edit)
mtb.qrcodes = append(mtb.qrcodes[:i], mtb.qrcodes[i+1:]...)
return nil
}
}
}
}
return nil
}
func (mtb *MoneroTipBot) saveGiveawayToFile() error {
file, err := json.MarshalIndent(mtb.giveaways, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile(viper.GetString("GIVEAWAY_FILE"), file, 0644)
}
func (mtb *MoneroTipBot) parsePhoto() error {
if !mtb.message.Chat.IsPrivate() {
// do nothing, since this is not in my PM
return nil
}
// received a photo.
msg := mtb.newReplyMessage(true)
file, err := mtb.bot.GetFile(tgbotapi.FileConfig{FileID: (*mtb.message.Photo)[len((*mtb.message.Photo))-1].FileID})
if err != nil {
msg.Text = "Weird. Couldn't get uploaded image path from telegram servers. This shouldn't happen."
return mtb.reply(msg)
}
res, err := http.Get(file.Link(viper.GetString("telegram_bot_token")))
if err != nil {
msg.Text = "Couldn't download uploaded image from telegram servers. Try again later."
return mtb.reply(msg)
}
now := time.Now().Unix()
//open a file for writing
savefile, err := os.Create(fmt.Sprintf("/tmp/qrcode.jpg_%d", now))
if err != nil {
msg.Text = "Could not create image file. Try again later."
return mtb.reply(msg)
}
_, err = io.Copy(savefile, res.Body)
if err != nil {
msg.Text = "Could not save image to file. Try again later."
return mtb.reply(msg)
}
savefile.Close()
defer os.Remove(savefile.Name())
qrimage, err := os.Open(fmt.Sprintf("/tmp/qrcode.jpg_%d", now))
if err != nil {
msg.Text = "Could not open image file. Try again later."
return mtb.reply(msg)
}
img, _, err := image.Decode(qrimage)
if err != nil {
msg.Text = "Could decode image."
return mtb.reply(msg)
}
// prepare BinaryBitmap
bmp, err := gozxing.NewBinaryBitmapFromImage(img)
if err != nil {
msg.Text = "Could not open image file. Try again later."
return mtb.reply(msg)
}
// decode image
qrReader := qrcode.NewQRCodeReader()
harder := map[gozxing.DecodeHintType]interface{}{gozxing.DecodeHintType_TRY_HARDER: true}
result, err := qrReader.Decode(bmp, harder)
if err != nil {
msg.Text = "Could not detect QR-Code in image."
return mtb.reply(msg)
}
parseuri, err := mtb.walletrpc.ParseURI(&wallet.RequestParseURI{URI: result.String()})
if err == nil {
if parseuri.URI.Amount == 0 {
msg.Text = parseuri.URI.Address
return mtb.reply(msg)
}
out := fmt.Sprintf("Address: %s\nAmount: %f XMR\nRecipient: %s\n\nDescription:\n%s", parseuri.URI.Address, wallet.XMRToFloat64(parseuri.URI.Amount), parseuri.URI.RecipientName, parseuri.URI.TxDescription)
claim := tgbotapi.NewInlineKeyboardButtonData("Send", "qrcode_tx_send")
cancel := tgbotapi.NewInlineKeyboardButtonData("Cancel", "qrcode_tx_cancel")
markup := tgbotapi.NewInlineKeyboardMarkup(tgbotapi.NewInlineKeyboardRow(claim, cancel))
msg := tgbotapi.NewMessage(mtb.message.Chat.ID, "")
msg.ReplyMarkup = markup
msg.Text = out
resp, _ := mtb.bot.Send(msg)
mtb.statsdIncr("qrcode_parsed.counter", 1)
qrcode := &QRCode{
Message: &resp,
From: mtb.message,
ParseURI: parseuri,
Amount: parseuri.URI.Amount,
}
mtb.qrcodes = append(mtb.qrcodes, qrcode)
} else {
msg.Text = "URI is not RFC 3986 compliant. Checking if string is a valid monero address."
mtb.reply(msg)
resp, err := mtb.walletrpc.ValidateAddress(&wallet.RequestValidateAddress{Address: result.String(), AnyNetType: viper.GetBool("IS_STAGENET_WALLET")})
if err != nil {
msg.Text = fmt.Sprintf("%s", err)
return mtb.reply(msg)
}
if resp.Valid {
msg.Text = "Found a valid monero address. Please copy and paste the following message back to me after filling in the right amount."
mtb.reply(msg)
msg.Format = false
msg.Text = fmt.Sprintf("/send %s AMOUNTHERE", result)
mtb.statsdIncr("qrcode_parsed.counter", 1)
return mtb.reply(msg)
}
msg.Text = "Address is not valid. Aborted."
mtb.statsdIncr("qrcode_invalid.counter", 1)
return mtb.reply(msg)
}
return nil
}
func (mtb *MoneroTipBot) listenRPC() {
notification := &Notification{}
for {
data, err := mtb.rpcchannel.RecvBytes(0)
if err != nil {
data, err := prepareErrorNotification(notification, err)
if err != nil {
continue
}
mtb.rpcchannel.SendBytes(data, 0)
continue
}
err = json.Unmarshal(data, notification)
if err != nil {
data, err := prepareErrorNotification(notification, err)
if err != nil {
continue
}
mtb.rpcchannel.SendBytes(data, 0)
continue
}
// process the notification message
msg := &Message{
Format: false,
ChatID: notification.UserID,
Text: notification.Message,
}
err = mtb.reply(msg)
if err != nil {
data, err := prepareErrorNotification(notification, err)
if err != nil {
continue
}
mtb.rpcchannel.SendBytes(data, 0)
continue
}
notification.Sent = true
data, err = json.Marshal(notification)
if err != nil {
data, err := prepareErrorNotification(notification, err)
if err != nil {
continue
}
mtb.rpcchannel.SendBytes(data, 0)
continue
}
_, err = mtb.rpcchannel.SendBytes(data, 0)
if err != nil {
continue
}
}
}
func prepareErrorNotification(notification *Notification, err error) ([]byte, error) {
notification.Sent = false
notification.Error = err.Error()
data, err := json.Marshal(notification)
if err != nil {
return nil, err
}
return data, nil
}
func groupTrackerLogger(tracker map[int64]*tgbotapi.Chat) {
for {
file, err := os.OpenFile(viper.GetString("LOGFILE"), os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
break
}
mutex.Lock()
for k, v := range tracker {
file.WriteString(fmt.Sprintf("Group ID: %d - Group Object: %#v\n", k, v))
}
mutex.Unlock()
file.Close()
time.Sleep(time.Minute * 60)
}
}
func (mtb *MoneroTipBot) statsdIncr(stat string, count int64, tags ...statsd.Tag) {
if viper.GetBool("USE_STATSD") {
mtb.statsdclient.Incr(stat, count, tags...)
}
}
func (mtb *MoneroTipBot) statsdGauge(stat string, value int64, tags ...statsd.Tag) {
if viper.GetBool("USE_STATSD") {
mtb.statsdclient.Gauge(stat, value, tags...)
}
}
func (mtb *MoneroTipBot) statsdFGauge(stat string, value float64, tags ...statsd.Tag) {
if viper.GetBool("USE_STATSD") {
mtb.statsdclient.FGauge(stat, value, tags...)
}
}
func (mtb *MoneroTipBot) statsdPrecisionTiming(stat string, delta time.Duration, tags ...statsd.Tag) {
if viper.GetBool("USE_STATSD") {
mtb.statsdclient.PrecisionTiming(stat, delta, tags...)
}
}