-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.js
2820 lines (2527 loc) · 157 KB
/
bot.js
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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { MessageAttachment, EmbedBuilder, Client, GatewayIntentBits, ButtonBuilder, SelectMenuBuilder, ActionRowBuilder, ClientUser, AttachmentBuilder } = require('discord.js');
const cron = require("cron");
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
var fs = require('fs');
var http = require('http');
const pngToJpeg = require('png-to-jpeg');
var mysql = require('mysql');
const cheerio = require('cheerio');
const Jimp = require('jimp');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] });
//create mysql connection
/*var con = mysql.createConnection({
host: "192.168.31.210",
user: "boyphongsakorn",
password: "team1556th",
database: "discordbot"
});*/
var con
let lottoapi = "http://192.168.31.210:5000";
let lotimgapi = "http://192.168.31.220:14000";
let apikey = process.env.rapidapikey;
//create a server object:
http.createServer(async function (req, res) {
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
'Access-Control-Max-Age': 2592000, // 30 days
/** add other headers as per requirement */
// set utf-8 encoding
'Content-Type': 'application/json; charset=utf-8'
};
if (req.url === '/count') {
res.writeHead(200, headers);
res.write(client.guilds.cache.size.toString()); //write a response to the client
res.end(); //end the response
} else if (req.url === '/botimage') {
console.log(client.user.avatarURL({ format: 'jpg', dynamic: true, size: 512 }));
await fetch(client.user.avatarURL({ format: 'jpg', dynamic: true, size: 512 }))
.then(res => res.arrayBuffer())
.then(buffer => {
const base64 = Buffer.from(buffer);
res.writeHead(200, { 'Content-Type': 'image/jpg' });
res.write(base64);
res.end();
});
} else if (req.url === '/guildlist') {
res.writeHead(200, headers);
//res.write(JSON.stringify(client.guilds.cache.map(guild => guild.name))); //write a response to the client
//response guild name and guild image url
let guildlist = client.guilds.cache.map(guild => {
return {
name: guild.name,
icon: guild.iconURL({ format: 'jpg', dynamic: true, size: 512 })
}
});
//shuffling array
guildlist.sort(() => Math.random() - 0.5);
res.write(JSON.stringify(guildlist)); //write a response to the client
res.end(); //end the response
} else {
res.writeHead(200, headers);
res.write('ok'); //write a response to the client
res.end(); //end the response
}
}).listen(8080); //the server object listens on port 8080
// functions
function padLeadingZeros(num, size) {
var s = num + "";
while (s.length < size) s = "0" + s;
return s;
}
function convertmonthtotext(month) {
switch (month) {
case '01': return "มกราคม"; break;
case '02': return "กุมภาพันธ์"; break;
case '03': return "มีนาคม"; break;
case '04': return "เมษายน"; break;
case '05': return "พฤษภาคม"; break;
case '06': return "มิถุนายน"; break;
case '07': return "กรกฎาคม"; break;
case '08': return "สิงหาคม"; break;
case '09': return "กันยายน"; break;
case '10': return "ตุลาคม"; break;
case '11': return "พฤศจิกายน"; break;
case '12': return "ธันวาคม"; break;
}
}
async function guildCommandCreate(guildid) {
//if guildid is array
if (Array.isArray(guildid)) {
for (let i = 0; i < guildid.length; i++) {
await guildCommandCreate(guildid[i]);
}
} else {
try {
const thatguild = client.guilds.cache.get(guildid);
let commands
if (thatguild) {
commands = thatguild.commands
} else {
commands = client.applications?.commands
}
/*commands?.create({
name: 'fthlotto',
description: "แจ้งเตือนสลากกินแบ่งรัฐบาลเวลาสี่โมงเย็นของวันทึ่ออก"
}, guildid)*/
commands?.create({
name: 'flottomode',
description: "ปรับโหมดการแจ้งเตือนสลากกินแบ่งฯ"
}, guildid)
/*commands?.create({
name: 'cthlotto',
description: "ยกเลิกแจ้งเตือนสลากกินแบ่งรัฐบาลของแชนแนลนี้"
}, guildid)*/
commands?.create({
name: 'subthlotto',
description: "ติดตาม/ยกเลิกการแจ้งเตือนสลากกินแบ่งฯ"
}, guildid)
commands?.create({
name: 'lastlotto',
description: "ดูสลากกินแบ่งรัฐบาลล่าสุด"
}, guildid)
commands?.create({
name: 'aithing',
description: "ดูเลขเด็ด 10 อันดับจากการใช้ Ai"
}, guildid)
commands?.create({
name: 'lotsheet',
description: "ใบตรวจสลากกินแบ่งรัฐบาล"
}, guildid)
commands?.create({
name: 'synumber',
description: "บันทึกเลขสลากฯที่คุณซื้อ เพื่อรับแจ้งเตือน",
options: [{
type: 3,
name: 'number',
description: 'ตัวเลขที่คุณซื้อหรือเลขที่คุณต้องการแจ้งเตือน (1 เลขต่อครั้ง)',
required: true
}]
}, guildid)
commands?.create({
name: 'srchlot',
description: "ตรวจสลากฯ ล่าสุดด้วยเลข",
options: [{
type: 3,
name: 'number',
description: 'ตัวเลขที่ต้องการตรวจสลากฯ',
required: true
}]
}, guildid)
commands?.create({
name: 'ตรวจสลากฯ',
type: 3
}, guildid)
commands?.create({
name: 'checkconnection',
description: 'เช็คการเชื่อมต่อ'
}, guildid)
commands?.create({
name: 'syhistory',
description: 'ประวัติการบันทึกสลากฯ'
}, guildid)
commands?.create({
name: 'lastthaioilprice',
description: 'ดูราคาน้ำมันล่าสุด'
}, guildid)
/*commands?.create({
name: 'fthaioilprice',
description: 'ติดตาม/แจ้งเตือนราคาน้ำมัน'
}, guildid)
commands?.create({
name: 'cthaioilprice',
description: 'ยกเลิกการแจ้งเตือนราคาน้ำมัน'
}, guildid)*/
commands?.create({
name: 'subthaioilprice',
description: 'ติดตาม/ยกเลิกการแจ้งเตือนราคาน้ำมัน'
}, guildid)
commands?.create({
name: 'checkblacklist',
description: 'ตรวจสอบรายชื่อคนโกง',
options: [{
type: 3,
name: 'search',
description: 'เลขประจำตัว/บัญชี/เบอร์/ชื่อคนโกง',
required: true
}]
}, guildid)
} catch (error) {
console.log('error: ' + error);
}
//return good
return true;
}
}
async function guildCommandDelete(guild) {
await guild.commands.fetch()
.then(async function (commands) {
await commands.forEach(command => {
command.delete()
.then(/*console.log*/)
.catch(console.error);
});
return true;
})
.catch((error) => {
console.log('error: ' + error);
return false;
});
}
async function guildCommandDeleteandCreate(guild) {
await guild.commands.fetch()
.then(async function (commands) {
await commands.forEach(command => {
command.delete()
.then(/*console.log*/)
.catch(console.error);
});
});
// wait 5 sec
await new Promise(resolve => setTimeout(resolve, 3000));
let guildid = guild.id;
await guildCommandCreate(guildid);
//return good
return true;
}
function handleDisconnect() {
con = mysql.createConnection({
host: "192.168.31.210",
user: "boyphongsakorn",
password: "team1556th",
database: "discordbot"
}); // Recreate the connection, since
// the old one cannot be reused.
con.connect(function (err) { // The server is either down
if (err) { // or restarting (takes a while sometimes).
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
} else {
console.log("Database Connected!");
} // to avoid a hot loop, and to allow our node script to
}); // process asynchronous requests in the meantime.
// If you're also serving http, display a 503 error.
con.on('error', function (err) {
console.log('db error', err);
if (err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect(); // lost due to either server restart, or a
} else { // connnection idle timeout (the wait_timeout
throw err; // server variable configures this)
}
});
}
// end functions
client.once('ready', () => {
handleDisconnect();
//con.connect(function (err) {
//if (err) throw err;
//console.log("Database Connected!");
//get all guilds
client.guilds.cache.forEach(async function (guild) {
try {
guild.commands.fetch().then(async function (commands) {
//if guild has no commands
if (commands.size != 13) {
//create commands
//await guildCommandCreate(guild.id);
await guildCommandDelete(guild);
await guildCommandCreate(guild.id);
}
});
} catch (error) {
console.log('error: ' + error);
}
});
//client.user.setPresence({ activities: [{ name: 'discordbot.pwisetthon.com' }], status: 'online' });
client.user.setPresence({ activities: [{ name: 'เจอปัญหาแจ้งได้ที่ discord.com/invite/j7xce5hxUf' }], status: 'online' });
//client.user.setPresence({ activities: [{ name: '📙 /lotsheet ใช้ได้แล้วนะ 👍' }], status: 'online' });
client.users.fetch('133439202556641280').then(dm => {
dm.send('Bot เริ่มต้นการทำงานแล้ว')
});
//send ok to channel 908708400379097184 and get message id
/*client.channels.cache.get('908708400379097184').send('Bot เริ่มต้นการทำงานแล้ว')
.then(async function (message) {
//log message id
console.log(message.id);
//wait 5 sec
await new Promise(resolve => setTimeout(resolve, 5000));
//delete message
client.channels.cache.get('908708400379097184').messages.cache.get(message.id).delete();
});*/
console.log('I am ready!');
//});
});
client.on("guildCreate", async guild => {
console.log("Joined a new guild: " + guild.id);
client.users.fetch('133439202556641280').then(dm => {
dm.send('ดิส ' + guild.name + '(' + guild.id + ') ได้เชิญ บอท PWisetthon.com เข้าเรียบร้อยแล้ว')
});
if (guild.systemChannelId != null && guild.systemChannelId != undefined) {
console.log("System Channel: " + guild.systemChannelId);
/*fetch(process.env.URL + '/discordbot/addchannels.php?chid=' + guild.systemChannelId)
.then(res => res.text())
.then(body => {
console.log(body);
if (body == 'debug') {
client.channels.cache.get(guild.systemChannelId).send('ขอบคุณ! ที่เชิญเราเข้าส่วนหนึ่งในดิสของคุณ')
.catch(console.error);
} else {
client.channels.cache.get(guild.systemChannelId).send('ขอบคุณ! ที่เชิญเราเข้าเป็นส่วนร่วมของดิสคุณ เราได้ทำการติดตามสลากฯให้สำหรับดิสนี้เรียบร้อยแล้ว! \nใช้คำสั่ง /subthlotto เพื่อยกเลิก')
.catch(console.error);
}
});*/
const fetchadd = await fetch(process.env.URL + '/discordbot/addchannels.php?chid=' + guild.systemChannelId)
const bodyadd = await fetchadd.text()
if (bodyadd == 'debug') {
client.channels.cache.get(guild.systemChannelId).send('ขอบคุณ! ที่เชิญเราเข้าส่วนหนึ่งในดิสของคุณ')
.catch(console.error);
} else {
client.channels.cache.get(guild.systemChannelId).send('ขอบคุณ! ที่เชิญเราเข้าเป็นส่วนร่วมของดิสคุณ เราได้ทำการติดตามสลากฯให้สำหรับดิสนี้เรียบร้อยแล้ว! \nใช้คำสั่ง /subthlotto เพื่อยกเลิก')
.catch(console.error);
}
}
//use guildCommandCreate
guildCommandCreate(guild.id);
})
let scheduledMessage = new cron.CronJob('* 15-17 * * *', async () => {
// datedata
let date = new Date().getDate();
let month = new Date().getMonth() + 1;
let year = new Date().getFullYear() + 543;
date = padLeadingZeros(date, 2);
month = padLeadingZeros(month, 2);
year = padLeadingZeros(year, 4);
let url = lottoapi + "/?date=" + date + "" + month + "" + year + "&fresh";
let settings = { "method": "GET" };
/*fetch(url, settings)
.then(res => res.json())
.then(async (json) => {*/
const fetchapi = await fetch(url, settings);
const json = await fetchapi.json();
console.log(json.length)
if (json.length == 7 || json.length == 8 || json.length == 9) {
if (json[0][1] == "0" || json[0][1] == 0 || json[0][1] == "xxxxxx" || json[0][1] == "XXXXXX" || isNaN(json[0][1])) {
/*client.users.fetch('133439202556641280').then(dm => {
dm.send('Bot ทำงานปกติและเช็คได้ว่าวันนี้หวยไม่ได้ออกหรือหวยยังออกไม่หมด')
})*/
if (json[0][1] == "xxxxxx" || json[0][1] == "XXXXXX") {
console.log('Bot ทำงานปกติและเช็คได้ว่าวันนี้หวยออกแต่ยังออกไม่หมด');
console.log('--------------------------------');
} else {
console.log('Bot ทำงานปกติและเช็คได้ว่าวันนี้หวยไม่ได้ออก');
console.log('--------------------------------');
var lasttime = null
try {
const stats = fs.statSync('lastout.txt');
//const expiry = new Date().getTime()
lasttime = stats.mtime
} catch (error) {
//console.log(error);
fs.writeFile('lastout.txt', '0', function (err) {
if (err) {
throw err
};
console.log('Saved!');
});
}
}
var fileContents = null;
try {
fileContents = fs.readFileSync('check.txt');
} catch (err) {
}
if (fileContents) {
if (fileContents != '0') {
fs.writeFile('check.txt', '0', function (err) {
if (err) {
throw err
};
console.log('Saved!');
});
}
} else {
fs.writeFile('check.txt', '0', function (err) {
if (err) {
throw err
};
console.log('Saved!');
});
}
} else {
//check every index of json has not "xxxxxx" or "XXXXXX"
for (let i = 0; i < json.length; i++) {
for (let j = 1; j < json[i].length; j++) {
if (json[i][j] == "xxxxxx" || json[i][j] == "XXXXXX") {
console.log('Bot ทำงานปกติและเช็คได้ว่าวันนี้หวยยังออกไม่หมด');
return;
}
}
}
let imgurl = 'https://screenshot-xi.vercel.app/api?date=';
console.log("หวยออกครบแล้ว")
var fileContents = null;
try {
fileContents = fs.readFileSync('check.txt');
} catch (err) {
fs.writeFileSync('check.txt', '0', function (err) {
if (err) {
throw err
};
console.log('Saved!');
});
}
var lasttime = null
try {
const stats = fs.statSync('lastout.txt');
//const expiry = new Date().getTime()
lasttime = stats.mtime
} catch (error) {
//console.log(error);
fs.writeFileSync('lastout.txt', '0', function (err) {
if (err) {
throw err
};
console.log('Saved!');
var d = new Date();
d.setDate(d.getDate() - 2);
fs.utimesSync(path.join(__dirname, 'lastout.txt'), new Date(), d)
const stats = fs.statSync('lastout.txt');
lasttime = stats.mtime
});
}
if (fileContents) {
let lastdatefromsql
con.query("SELECT * FROM lott_round ORDER BY round DESC LIMIT 1", function (err, result, fields) {
if (err) throw err;
//console.log(result);
lastdatefromsql = result[0].round; //YYYY-MM-DD
});
let today = new Date();
// convert today to yyyy-mm-dd
let dd = today.getDate();
let mm = today.getMonth() + 1; //January is 0!
let yyyy = today.getFullYear();
dd = padLeadingZeros(dd, 2);
mm = padLeadingZeros(mm, 2);
todayformat = yyyy + '-' + mm + '-' + dd;
if (lasttime == null) {
lasttime = new Date();
//minus 2 days
lasttime.setDate(lasttime.getDate() - 2);
}
if (fileContents != "1" && (lasttime.toDateString() != today.toDateString() || todayformat != lastdatefromsql)) {
fs.writeFile('check.txt', '1', function (err) {
if (err) {
throw err
};
console.log('Saved!');
});
fs.writeFile('lastout.txt', '1', function (err) {
if (err) {
throw err
};
console.log('Saved!');
});
//if (fs.existsSync('./lottery_' + date + '' + month + '' + year + '.png') == false) {
/*await fetch('https://screenshot-xi.vercel.app/api?date=' + date + '' + month + '' + year)
.then(res => res.buffer())
.then(async (res) => {
await fs.writeFileSync('./lottery_' + date + '' + month + '' + year + '.png', res)
})
.catch(async (err) => {
console.log('Error:', err.message)
});*/
// const normalimg = await fetch('https://screenshot-xi.vercel.app/api?date=' + date + '' + month + '' + year)
// const normalimg = await fetch('https://anywhere.pwisetthon.com/http://108.61.183.221:8080/?date=' + date + '' + month + '' + year)
const normalimg = await fetch('https://lotimg.pwisetthon.com/?date=' + date + '' + month + '' + year)
const bufimg = await normalimg.arrayBuffer()
/*await fetch('https://lotimg.pwisetthon.com/?date=' + date + '' + month + '' + year + '&mode=gold')
.then(res => res.buffer())
.then(async (res) => {
await fs.writeFileSync('./lottery_' + date + '' + month + '' + year + '_gold.png', res)
})
.catch(async (err) => {
console.log('Error:', err.message)
});*/
const goldimg = await fetch('https://lotimg.pwisetthon.com/?date=' + date + '' + month + '' + year + '&mode=gold')
const bufgoldimg = await goldimg.arrayBuffer()
//}
console.log(Buffer.from(bufimg).length)
console.log(Buffer.from(bufgoldimg).length)
//Buffer.from(bufimg).length is low to be image then kill process or goldimg is not image type
if (Buffer.from(bufimg).length < 1000 || Buffer.from(bufgoldimg).length < 1000 || normalimg.status != 200 || goldimg.status != 200) {
fs.writeFile('check.txt', '0', function (err) {
if (err) {
throw err
};
console.log('Saved!');
});
fs.writeFile('lastout.txt', '0', function (err) {
if (err) {
throw err
};
console.log('Saved!');
});
process.exit(1);
}
//check number user save
// con.query("SELECT * FROM lott_table WHERE status = 'waiting'", async function (err, result, fields) {
const result = await con.query("SELECT * FROM lott_table WHERE status = 'waiting'", async function (err, result, fields) {
return result
});
// if (err) throw err;
console.log(result);
//loop result
for (let i = 0; i < result.length; i++) {
let whatid = result[i].lott_id
let discordid = result[i].discord_id
let numberhebuy = result[i].numberbuy
console.log(result[i].lott_id)
console.log(result[i].numberbuy)
let optitot = { "method": "GET", "headers": { "x-rapidapi-host": "thai-lottery1.p.rapidapi.com", "x-rapidapi-key": apikey } };
/*fetch("https://thai-lottery1.p.rapidapi.com/checklottery?by=" + date + "" + month + "" + year + "&search=" + result[i].numberbuy, optitot)
.then(res => res.text())
.then((json) => {
//if json is null or empty send message to result[i].discord_id
if (json == '' || json == null) {
var sql = "UPDATE lott_table SET status = 'ไม่ถูก',lotround = '" + (year - 543) + "-" + month + "-" + date + "' WHERE lott_id = '" + whatid + "'";
con.query(sql, function (err, result) {
if (err) throw err;
client.users.fetch(discordid).then(dm => {
dm.send('ขออภัยค่ะ! เลข ' + numberhebuy + ' ยังไม่ถูกรางวัลในงวดวันนี้ค่ะ')
})
});
} else {
var sql = "UPDATE lott_table SET status = 'win',lotround = '" + (year - 543) + "-" + month + "-" + date + "' WHERE lott_id = '" + whatid + "'";
con.query(sql, function (err, result) {
if (err) throw err;
client.users.fetch(discordid).then(dm => {
dm.send('ยินดีด้วย! เลข ' + numberhebuy + ' ถูกรางวัลในงวดวันนี้ค่ะ')
})
});
}
});*/
// const checkapi = await fetch('https://thai-lottery1.p.rapidapi.com/checklottery?by=' + date + '' + month + '' + year + '&search=' + result[i].numberbuy, optitot)
const checkapi = await fetch('https://lotapi.pwisetthon.com/checklottery?by=' + date + '' + month + '' + year + '&search=' + result[i].numberbuy)
try {
const checkjson = await checkapi.json()
} catch (error) {
fs.writeFile('check.txt', '0', function (err) {
if (err) {
throw err
};
console.log('Saved!');
});
fs.writeFile('lastout.txt', '0', function (err) {
if (err) {
throw err
};
console.log('Saved!');
});
process.exit(1);
}
const checkjson = await checkapi.json()
if (checkjson == '' || checkjson == null || checkjson == {} || checkjson == [] || checkjson.length == 0) {
var sql = "UPDATE lott_table SET status = 'ไม่ถูก',lotround = '" + (year - 543) + "-" + month + "-" + date + "' WHERE lott_id = '" + whatid + "'";
con.query(sql, function (err, result) {
if (err) throw err;
client.users.fetch(discordid).then(dm => {
dm.send('ขออภัยค่ะ! เลข ' + numberhebuy + ' ยังไม่ถูกรางวัลในงวดวันนี้ค่ะ')
})
});
} else {
var sql = "UPDATE lott_table SET status = 'win',lotround = '" + (year - 543) + "-" + month + "-" + date + "' WHERE lott_id = '" + whatid + "'";
con.query(sql, function (err, result) {
if (err) throw err;
client.users.fetch(discordid).then(dm => {
dm.send('ยินดีด้วย! เลข ' + numberhebuy + ' ถูกรางวัลในงวดวันนี้ค่ะ')
})
});
}
}
// });
//const file = new MessageAttachment('./lottery_' + date + '' + month + '' + year + '.png');
//const file = new AttachmentBuilder('./lottery_' + date + '' + month + '' + year + '.png');
const file = new AttachmentBuilder(Buffer.from(bufimg), { name: 'lottery_' + date + '' + month + '' + year + '.png' });
//const filegold = new MessageAttachment('./lottery_' + date + '' + month + '' + year + '_gold.png');
//const filegold = new AttachmentBuilder('./lottery_' + date + '' + month + '' + year + '_gold.png');
const filegold = new AttachmentBuilder(Buffer.from(bufgoldimg), { name: 'lottery_' + date + '' + month + '' + year + '_gold.png' });
const msg = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('ผลสลากกินแบ่งรัฐบาล')
.setURL('https://www.glo.or.th/')
.setDescription('งวดวันที่ ' + new Date().getDate() + ' ' + convertmonthtotext(month) + ' ' + year)
.setThumbnail('https://raw.githubusercontent.com/boyphongsakorn/pwisetthon-discord-bot/master/docs/glologo.png')
.addFields(
{ name: 'รางวัลที่หนึ่ง', value: json[0][1] },
//{ name: '\u200B', value: '\u200B' },
{ name: 'เลขหน้าสามตัว', value: json[1][1] + ' | ' + json[1][2], inline: true },
{ name: 'เลขท้ายสามตัว', value: json[2][1] + ' | ' + json[2][2], inline: true },
{ name: 'เลขท้ายสองตัว', value: json[3][1] },
)
//.setImage('https://img.gs/fhcphvsghs/full,quality=low/' + imgurl + date + month + year)
.setImage('attachment://lottery_' + date + '' + month + '' + year + '.png')
.setTimestamp()
//.setFooter('ข้อมูลจาก rapidapi.com/boyphongsakorn/api/thai-lottery1 \nบอทจัดทำโดย Phongsakorn Wisetthon \nให้ค่ากาแฟ buymeacoffee.com/boyphongsakorn');
.setFooter({ text: 'ข้อมูลจาก rapidapi.com/boyphongsakorn/api/thai-lottery1 \nบอทจัดทำโดย TeamQuadB.in.th \nให้ค่ากาแฟ buymeacoffee.com/boyphongsakorn' });
const msggold = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('ผลสลากกินแบ่งรัฐบาล')
.setURL('https://www.glo.or.th/')
.setDescription('งวดวันที่ ' + new Date().getDate() + ' ' + convertmonthtotext(month) + ' ' + year)
.setThumbnail('https://raw.githubusercontent.com/boyphongsakorn/pwisetthon-discord-bot/master/docs/glologo.png')
.addFields(
{ name: 'รางวัลที่หนึ่ง', value: json[0][1] },
//{ name: '\u200B', value: '\u200B' },
{ name: 'เลขหน้าสามตัว', value: json[1][1] + ' | ' + json[1][2], inline: true },
{ name: 'เลขท้ายสามตัว', value: json[2][1] + ' | ' + json[2][2], inline: true },
{ name: 'เลขท้ายสองตัว', value: json[3][1] },
)
//.setImage('https://img.gs/fhcphvsghs/full,quality=low/' + imgurl + date + month + year)
.setImage('attachment://lottery_' + date + '' + month + '' + year + '_gold.png')
.setTimestamp()
//.setFooter('ข้อมูลจาก rapidapi.com/boyphongsakorn/api/thai-lottery1 \nบอทจัดทำโดย Phongsakorn Wisetthon \nให้ค่ากาแฟ buymeacoffee.com/boyphongsakorn');
.setFooter({ text: 'ข้อมูลจาก rapidapi.com/boyphongsakorn/api/thai-lottery1 \nบอทจัดทำโดย TeamQuadB.in.th \nให้ค่ากาแฟ buymeacoffee.com/boyphongsakorn' });
const response = await fetch(process.env.URL + '/discordbot/chlist.txt', { method: 'GET' });
const data = await response.json();
const wow = data;
//loop [1,2,3] array
for (let i = 0; i < data.length; i++) {
let unknows = 0;
try {
console.log(client.channels.fetch(wow[i]).then(channel => {
console.log(channel.guildId)
unknows = channel.guildId;
}).catch(console.error));
} catch (error) {
unknows = 0;
}
//wait 3 sec
await new Promise(r => setTimeout(r, 3000));
if (unknows != 0) {
con.query("SELECT * FROM lott_main WHERE lott_guildid = '" + unknows + "'", function (err, result, fields) {
//if (err) throw err;
if (result.length == 0 || result[0].lott_resultmode == 'normal' || err) {
if (err) {
console.log(err);
}
try {
client.channels.cache.get(wow[i]).send({ embeds: [msg], files: [file] })
.then((log) => {
console.log(log);
})
.catch((error) => {
});
} catch (error) {
console.log('don\'t send')
}
} else {
try {
client.channels.cache.get(wow[i]).send({ embeds: [msggold], files: [filegold] })
.then((log) => {
console.log(log);
})
.catch((error) => {
});
} catch (error) {
console.log('don\'t send')
}
}
})
} else {
try {
client.channels.cache.get(wow[i]).send({ embeds: [msg], files: [file] })
.then((log) => {
console.log(log);
})
.catch((error) => {
console.log(error);
});
} catch (error) {
console.log('don\'t send')
}
}
}
//insert to sql
con.query("INSERT INTO lott_round (id, round) VALUES ('" + date + "" + month + "" + year + "', '" + todayformat + "')", function (err, result, fields) {
if (err) throw err;
//console.log(result);
console.log('Insert complete');
});
}
}
}
}
//});
});
// When you want to start it, use:
scheduledMessage.start()
// You could also make a command to pause and resume the job
//thaioilprice cron
let scheduledthaioil = new cron.CronJob('* 05-18 * * *', async () => {
let nows = new Date();
//is 5 in morning
if (nows.getHours() == 5 && nows.getMinutes() == 0) {
if (nows.getDate() >= 1 && nows.getDate() <= 3 && nows.getMonth() == 0) {
// วันปีใหม่
client.user.setAvatar('https://img.gs/fhcphvsghs/512/https://raw.githubusercontent.com/boyphongsakorn/pwisetthon-discord-bot/master/img/botav_mrahny.jpg')
client.user.setActivity('สุขสันต์วันปีใหม่ ' + (nows.getFullYear() + 543), { type: 'PLAYING' });
} else if (nows.getDate() >= 1 && nows.getDate() <= 3 && nows.getMonth() == 1) {
// วันเกิด
client.user.setAvatar('https://img.gs/fhcphvsghs/512/https://raw.githubusercontent.com/boyphongsakorn/pwisetthon-discord-bot/master/img/botav_hbd.jpg')
} else if (nows.getDate() >= 7 && nows.getDate() <= 11 && nows.getMonth() == 1) {
// วันตรุษจีน
client.user.setAvatar('https://img.gs/fhcphvsghs/512/https://raw.githubusercontent.com/boyphongsakorn/pwisetthon-discord-bot/master/img/botav_cny.png')
} else if (nows.getDate() >= 13 && nows.getDate() <= 15 && nows.getMonth() == 1) {
// วันวาเลนไทน์
client.user.setAvatar('https://img.gs/fhcphvsghs/512/https://raw.githubusercontent.com/boyphongsakorn/pwisetthon-discord-bot/master/img/botav_vd.png')
} else if (nows.getDate() >= 24 && nows.getDate() <= 26 && nows.getMonth() == 1) {
// วันมาฆบูชา
client.user.setAvatar('https://img.gs/fhcphvsghs/512/https://raw.githubusercontent.com/boyphongsakorn/pwisetthon-discord-bot/master/img/botav_makha.jpg')
} else if (nows.getDate() >= 5 && nows.getDate() <= 7 && nows.getMonth() == 3) {
// วันจักรี
client.user.setAvatar('https://img.gs/fhcphvsghs/512/https://raw.githubusercontent.com/boyphongsakorn/pwisetthon-discord-bot/master/img/botav_ckd.png')
} else if (nows.getDate() >= 11 && nows.getDate() <= 15 && nows.getMonth() == 3) {
// วันสงกรานต์
client.user.setAvatar('https://img.gs/fhcphvsghs/512/https://raw.githubusercontent.com/boyphongsakorn/pwisetthon-discord-bot/master/img/botav_songkran.jpg')
} else if (nows.getDate() >= 1 && nows.getDate() <= 3 && nows.getMonth() == 4) {
// วันแรงงาน
client.user.setAvatar('https://img.gs/fhcphvsghs/512/https://raw.githubusercontent.com/boyphongsakorn/pwisetthon-discord-bot/master/img/botav_lod.png')
} else if (nows.getDate() >= 21 && nows.getDate() <= 23 && nows.getMonth() == 9) {
// วันวิสาขบูชา
client.user.setAvatar('https://img.gs/fhcphvsghs/512/https://raw.githubusercontent.com/boyphongsakorn/pwisetthon-discord-bot/master/img/botav_piya.jpg')
} else if ((nows.getDate() >= 30 && nows.getDate() <= 31 && nows.getMonth() == 9) || (nows.getDate() == 1 && nows.getMonth() == 10)) {
// วันฮาโลวีน
client.user.setAvatar('https://img.gs/fhcphvsghs/512/https://raw.githubusercontent.com/boyphongsakorn/pwisetthon-discord-bot/master/img/botav_hh.jpg')
} else if (nows.getDate() >= 26 && nows.getDate() <= 28 && nows.getMonth() == 10) {
// วันลอยกระทง
client.user.setAvatar('https://img.gs/fhcphvsghs/512/https://raw.githubusercontent.com/boyphongsakorn/pwisetthon-discord-bot/master/img/botav_vsd.png')
} else if (nows.getDate() >= 8 && nows.getDate() <= 10 && nows.getMonth() == 11) {
// วันรัฐธรรมนูญ
client.user.setAvatar('https://img.gs/fhcphvsghs/512/https://raw.githubusercontent.com/boyphongsakorn/pwisetthon-discord-bot/master/img/botav_law.jpg')
} else if ((nows.getDate() >= 23 && nows.getDate() <= 31 && nows.getMonth() == 11) || (nows.getDate() == 1 && nows.getMonth() == 0)) {
// วันคริสมาสต์ และ วันปีใหม่
client.user.setAvatar('https://img.gs/fhcphvsghs/512/https://raw.githubusercontent.com/boyphongsakorn/pwisetthon-discord-bot/master/img/botav_mrahny.jpg')
if (nows.getDate() >= 24 && nows.getDate() <= 25) {
client.user.setActivity('🎄🎅🎁🎉🎊🎆🎇🧨🎈🎄', { type: 'PLAYING' });
} else if (nows.getDate() >= 26 && nows.getDate() <= 31) {
client.user.setActivity('Happy New Year ' + (nows.getFullYear() + 543), { type: 'PLAYING' });
} else if (nows.getDate() == 1) {
client.user.setActivity('สุขสันต์วันปีใหม่ ' + (nows.getFullYear() + 543), { type: 'PLAYING' });
}
} else {
client.user.setAvatar('https://img.gs/fhcphvsghs/512/https://raw.githubusercontent.com/boyphongsakorn/pwisetthon-discord-bot/master/img/botav.jpg')
}
}
//fetch http://192.168.31.210:1000 || https://topapi.pwisetthon.com
/*fetch('https://thaioilpriceapi-vercel.vercel.app')
.then(res => res.json())
.then(json => {*/
try {
const fetchapi = await fetch('https://topapi.pwisetthon.com');
const json = await fetchapi.json();
let ngv = json[0][10].replace('~', '');
const response = await fetch(process.env.URL + '/discordbot/oilchlist.txt');
const data = await response.json();
const wow = data;
var sql = 'SELECT * FROM oilprice WHERE date = "' + json[0][0] + '"';
con.query(sql, function (err, result) {
if (err) throw err;
if (result.length == 0 && json[0][0] != '') {
console.log('hey new oil price has come');
if (json[0][10] == '-') {
ngv = 0
}
var sql = 'INSERT INTO oilprice VALUES ("' + json[0][0] + '", ' + json[0][1] + ', ' + json[0][2] + ', ' + json[0][3] + ', ' + json[0][4] + ', ' + json[0][5] + ', ' + json[0][6] + ', ' + json[0][7] + ', ' + json[0][8] + ', ' + ngv + ')';
con.query(sql, async function (err, result) {
if (err) {
var deletesql = 'DELETE FROM oilprice WHERE date = "' + json[0][0] + '"';
con.query(deletesql, function (err, result) {
if (err) throw err;
console.log('Deleted!');
});
return;
}
//set Presence
if (parseInt(json[2][8]) > 0) {
client.user.setPresence({ activities: [{ name: 'เซ็ง 91 ขึ้นอีกละ | discordbot.pwisetthon.com' }], status: 'online' });
//after 1 hour set back to default
setTimeout(() => {
client.user.setPresence({ activities: [{ name: 'discordbot.pwisetthon.com' }], status: 'online' });
}, 3600000);
}
//let imagegood = false;
/*await fetch('https://screenshot-xi.vercel.app/api?url=https://boyphongsakorn.github.io/thaioilpriceapi&width=1000&height=1000', { timeout: 7500 })
.then(res => res.buffer())
.then(async (res) => {
await fs.writeFileSync('./lastoilprice.png', res)
//imagegood = true;
})
.catch(async (err) => {
console.log(err);
//imagegood = false;
});*/
let downloadscussess = false;
let thaioilimg
while (downloadscussess == false) {
try {
//const fetchthaioilimg = await fetch('https://screenshot-xi.vercel.app/api?url=https://boyphongsakorn.github.io/thaioilpriceapi&width=1000&height=1000');
const fetchthaioilimg = await fetch('https://topapi.pwisetthon.com/image');
thaioilimg = await fetchthaioilimg.arrayBuffer();
if (Buffer.from(thaioilimg).length > 100000) {
downloadscussess = true;
}
} catch (err) {
console.log(err);
}
}
//const fetchthaioilimg = await fetch('https://topapi.pwisetthon.com/image');
//const thaioilimg = await fetchthaioilimg.arrayBuffer();
//let files
//let imageisgood = false
//check if file exist and size > 400kb and size < 500kb
/*if (fs.existsSync('./lastoilprice.png') && fs.statSync('./lastoilprice.png').size > 400000 && fs.statSync('./lastoilprice.png').size < 500000) {
//files = new MessageAttachment('./lastoilprice.png');
imagegood = true
} else {
imagegood = false;
await fetch('https://topapi.pwisetthon.com/image')
.then(res => res.buffer())
.then(async (res) => {
await fs.writeFileSync('./lastoilprice.png', res)
//files = new MessageAttachment('./lastoilprice.png');
imagegood = true;
})
}*/
let todays = new Date();
let oilday = new Date(json[0][0].substring(6, 10) + '-' + json[0][0].substring(3, 5) + '-' + json[0][0].substring(0, 2));
let desctext
//if todays == oilday
if (todays.getDate() == oilday.getDate()) {
desctext = 'นี้';
} else if (todays.getDate() > oilday.getDate()) {
desctext = 'เมื่อวานนี้';
} else {
desctext = 'พรุ่งนี้';
}
//const files = new MessageAttachment('./lastoilprice.png');
//const files = new AttachmentBuilder('./lastoilprice.png');
const files = new AttachmentBuilder(Buffer.from(thaioilimg), { name: 'lastoilprice.png' });
let msg = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('ราคาน้ำมันวัน' + desctext)
.setURL('https://www.bangchak.co.th/th/oilprice/historical')
.setDescription('ราคาน้ำมันมีการเปลี่ยนแปลงสำหรับวัน' + desctext + ' (วันที่ ' + parseInt(json[0][0].substring(0, 2)) + ' ' + convertmonthtotext(json[0][0].substring(3, 5)) + ' ' + json[0][0].substring(6, 10) + ')')
.setThumbnail('https://www.bangchak.co.th/glide/assets/images/defaults/opengraph.png?h=350&fit=max&fm=jpg&t=1650602255')
.setImage('attachment://lastoilprice.png')
.setTimestamp()
.setFooter({ text: 'ข้อมูลจาก bangchak.co.th \nบอทจัดทำโดย TeamQuadB.in.th \nให้ค่ากาแฟ buymeacoffee.com/boyphongsakorn' });
/*if (imagegood == false) {
msg.setImage('https://screenshot-xi.vercel.app/api?url=https://boyphongsakorn.github.io/thaioilpriceapi&width=1000&height=1000')
}*/
let messid = [];
for (let i = 0; i < wow.length; i++) {
try {
//if (imagegood == true) {
await client.channels.cache.get(wow[i]).send({ embeds: [msg], files: [files] })
.then((log) => {
//console.log(log);
//push message id and channel id to messid
messid.push({
messid: log.id,
chanelid: wow[i]
})
})
.catch((error) => {
//console.log(error);