-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_init_final.py
4294 lines (3627 loc) · 173 KB
/
test_init_final.py
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
# -*- coding: utf-8 -*-
################ Server Ver. 28 (2021. 6. 23.) #####################
import sys, os, ctypes
import asyncio, discord, aiohttp
import random, re, datetime, time, logging
from discord.ext import tasks, commands
from discord.ext.commands import CommandNotFound, MissingRequiredArgument
from gtts import gTTS
from github import Github
import base64
import gspread, boto3
from oauth2client.service_account import ServiceAccountCredentials #정산
from io import StringIO
import urllib.request
from math import ceil, floor
##################### 로깅 ###########################
log_stream = StringIO()
logging.basicConfig(stream=log_stream, level=logging.WARNING)
#ilsanglog = logging.getLogger('discord')
#ilsanglog.setLevel(level = logging.WARNING)
#handler = logging.StreamHandler()
#handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
#ilsanglog.addHandler(handler)
#####################################################
if not discord.opus.is_loaded():
discord.opus.load_opus(ctypes.util.find_library('opus'))
print("opus_loaded")
basicSetting = []
bossData = []
fixed_bossData = []
bossNum = 0
fixed_bossNum = 0
chkvoicechannel = 0
chkrelogin = 0
chflg = 0
LoadChk = 0
bossTime = []
tmp_bossTime = []
fixed_bossTime = []
bossTimeString = []
bossDateString = []
tmp_bossTimeString = []
tmp_bossDateString = []
bossFlag = []
bossFlag0 = []
fixed_bossFlag = []
fixed_bossFlag0 = []
bossMungFlag = []
bossMungCnt = []
channel_info = []
channel_name = []
channel_id = []
channel_voice_name = []
channel_voice_id = []
channel_type = []
FixedBossDateData = []
indexFixedBossname = []
endTime = None
gc = None
credentials = None
regenembed = None
command = None
kill_Data = None
kill_Time = None
item_Data = None
tmp_racing_unit = None
setting_channel_name = None
boss_nick = {}
access_token = os.environ["BOT_TOKEN"]
git_access_token = os.environ["GIT_TOKEN"]
git_access_repo = os.environ["GIT_REPO"]
git_access_repo_restart = os.environ["GIT_REPO_RESTART"]
try:
aws_key = os.environ["AWS_KEY"]
aws_secret_key = os.environ["AWS_SECRET_KEY"]
except:
aws_key = ""
aws_secret_key = ""
g = Github(git_access_token)
repo = g.get_repo(git_access_repo)
repo_restart = g.get_repo(git_access_repo_restart)
#초성추출 함수
def convertToInitialLetters(text):
CHOSUNG_START_LETTER = 4352
JAMO_START_LETTER = 44032
JAMO_END_LETTER = 55203
JAMO_CYCLE = 588
def isHangul(ch):
return ord(ch) >= JAMO_START_LETTER and ord(ch) <= JAMO_END_LETTER
def isBlankOrNumber(ch):
return ord(ch) == 32 or ord(ch) >= 48 and ord(ch) <= 57
def convertNomalInitialLetter(ch):
dic_InitalLetter = {4352:"ㄱ"
,4353:"ㄲ"
,4354:"ㄴ"
,4355:"ㄷ"
,4356:"ㄸ"
,4357:"ㄹ"
,4358:"ㅁ"
,4359:"ㅂ"
,4360:"ㅃ"
,4361:"ㅅ"
,4362:"ㅆ"
,4363:"ㅇ"
,4364:"ㅈ"
,4365:"ㅉ"
,4366:"ㅊ"
,4367:"ㅋ"
,4368:"ㅌ"
,4369:"ㅍ"
,4370:"ㅎ"
,32:" "
,48:"0"
,49:"1"
,50:"2"
,51:"3"
,52:"4"
,53:"5"
,54:"6"
,55:"7"
,56:"8"
,57:"9"
}
return dic_InitalLetter[ord(ch)]
result = ""
for ch in text:
if isHangul(ch): #한글이 아닌 글자는 걸러냅니다.
result += convertNomalInitialLetter(chr((int((ord(ch)-JAMO_START_LETTER)/JAMO_CYCLE))+CHOSUNG_START_LETTER))
elif isBlankOrNumber(ch):
result += convertNomalInitialLetter(chr(int(ord(ch))))
return result
def init():
global basicSetting
global bossData
global fixed_bossData
global bossNum
global fixed_bossNum
global chkvoicechannel
global chkrelogin
global bossTime
global tmp_bossTime
global fixed_bossTime
global bossTimeString
global bossDateString
global tmp_bossTimeString
global tmp_bossDateString
global bossFlag
global bossFlag0
global fixed_bossFlag
global fixed_bossFlag0
global bossMungFlag
global bossMungCnt
global channel_info
global channel_name
global channel_voice_name
global channel_voice_id
global channel_id
global channel_type
global LoadChk
global indexFixedBossname
global FixedBossDateData
global endTime
global gc #정산
global credentials #정산
global regenembed
global command
global kill_Data
global kill_Time
global item_Data
global tmp_racing_unit
global boss_nick
command = []
tmp_bossData = []
tmp_fixed_bossData = []
FixedBossDateData = []
indexFixedBossname = []
kill_Data = {}
tmp_kill_Data = []
item_Data = {}
tmp_item_Data = []
f = []
fb = []
fk = []
fc = []
fi = []
tmp_racing_unit = []
boss_nick = {}
inidata = repo.get_contents("test_setting.ini")
file_data1 = base64.b64decode(inidata.content)
file_data1 = file_data1.decode('utf-8')
inputData = file_data1.split('\n')
command_inidata = repo.get_contents("command.ini")
file_data4 = base64.b64decode(command_inidata.content)
file_data4 = file_data4.decode('utf-8')
command_inputData = file_data4.split('\n')
boss_inidata = repo.get_contents("boss.ini")
file_data3 = base64.b64decode(boss_inidata.content)
file_data3 = file_data3.decode('utf-8')
boss_inputData = file_data3.split('\n')
fixed_inidata = repo.get_contents("fixed_boss.ini")
file_data2 = base64.b64decode(fixed_inidata.content)
file_data2 = file_data2.decode('utf-8')
fixed_inputData = file_data2.split('\n')
kill_inidata = repo.get_contents("kill_list.ini")
file_data5 = base64.b64decode(kill_inidata.content)
file_data5 = file_data5.decode('utf-8')
kill_inputData = file_data5.split('\n')
item_inidata = repo.get_contents("item_list.ini")
file_data6 = base64.b64decode(item_inidata.content)
file_data6 = file_data6.decode('utf-8')
item_inputData = file_data6.split('\n')
for i in range(len(fixed_inputData)):
FixedBossDateData.append(fixed_inputData[i])
index_fixed = 0
for value in FixedBossDateData:
if value.find('bossname') != -1:
indexFixedBossname.append(index_fixed)
index_fixed = index_fixed + 1
for i in range(inputData.count('\r')):
inputData.remove('\r')
for i in range(command_inputData.count('\r')):
command_inputData.remove('\r')
for i in range(boss_inputData.count('\r')):
boss_inputData.remove('\r')
for i in range(fixed_inputData.count('\r')):
fixed_inputData.remove('\r')
for i in range(kill_inputData.count('\r')):
kill_inputData.remove('\r')
for i in range(item_inputData.count('\r')):
item_inputData.remove('\r')
del(command_inputData[0])
del(boss_inputData[0])
del(fixed_inputData[0])
del(kill_inputData[0])
del(item_inputData[0])
for data in boss_inputData:
if "kakaoOnOff" in data:
raise Exception("[boss.ini] 파일에서 [kakaoOnOff]를 지워주세요.")
for data in fixed_inputData:
if "kakaoOnOff" in data:
raise Exception("[fixed_boss.ini] 파일에서 [kakaoOnOff]를 지워주세요.")
############## 보탐봇 초기 설정 리스트 #####################
try:
basicSetting.append(inputData[0][11:]) #basicSetting[0] : timezone
basicSetting.append(inputData[8][15:]) #basicSetting[1] : before_alert
basicSetting.append(inputData[10][11:]) #basicSetting[2] : mungChk1
basicSetting.append(inputData[9][16:]) #basicSetting[3] : before_alert1
basicSetting.append(inputData[14][14:16]) #basicSetting[4] : restarttime 시
basicSetting.append(inputData[14][17:]) #basicSetting[5] : restarttime 분
basicSetting.append(inputData[1][15:]) #basicSetting[6] : voice채널 ID
basicSetting.append(inputData[2][14:]) #basicSetting[7] : text채널 ID
basicSetting.append(inputData[3][16:]) #basicSetting[8] : 사다리 채널 ID
basicSetting.append(inputData[13][14:]) #basicSetting[9] : !ㅂ 출력 수
basicSetting.append(inputData[17][11:]) #basicSetting[10] : json 파일명
basicSetting.append(inputData[4][17:]) #basicSetting[11] : 정산 채널 ID
basicSetting.append(inputData[16][12:]) #basicSetting[12] : sheet 이름
basicSetting.append(inputData[15][16:]) #basicSetting[13] : restart 주기
basicSetting.append(inputData[18][12:]) #basicSetting[14] : 시트 이름
basicSetting.append(inputData[19][12:]) #basicSetting[15] : 입력 셀
basicSetting.append(inputData[20][13:]) #basicSetting[16] : 출력 셀
basicSetting.append(inputData[12][13:]) #basicSetting[17] : 멍삭제횟수
basicSetting.append(inputData[5][14:]) #basicSetting[18] : kill채널 ID
basicSetting.append(inputData[6][16:]) #basicSetting[19] : racing 채널 ID
basicSetting.append(inputData[7][14:]) #basicSetting[20] : item 채널 ID
basicSetting.append(inputData[21][12:]) #basicSetting[21] : voice_use
basicSetting.append(inputData[11][11:]) #basicSetting[22] : mungChk2
except:
raise Exception("[test_setting.ini] 파일 양식을 확인하세요.")
############## 보탐봇 명령어 리스트 #####################
for i in range(len(command_inputData)):
tmp_command = command_inputData[i][12:].rstrip('\r')
fc = tmp_command.split(', ')
command.append(fc)
fc = []
#command.append(command_inputData[i][12:].rstrip('\r')) #command[0] ~ [24] : 명령어
################## 척살 명단 ###########################
for i in range(len(kill_inputData)):
tmp_kill_Data.append(kill_inputData[i].rstrip('\r'))
fk.append(tmp_kill_Data[i][:tmp_kill_Data[i].find(' ')])
fk.append(tmp_kill_Data[i][tmp_kill_Data[i].find(' ')+1:])
try:
kill_Data[fk[0]] = int(fk[1])
except:
pass
fk = []
for i in range(len(item_inputData)):
tmp_item_Data.append(item_inputData[i].rstrip('\r'))
fi.append(tmp_item_Data[i][:tmp_item_Data[i].find(' ')])
fi.append(tmp_item_Data[i][tmp_item_Data[i].find(' ')+1:])
try:
item_Data[fi[0]] = int(fi[1])
except:
pass
fi = []
tmp_killtime = datetime.datetime.now().replace(hour=int(5), minute=int(0), second = int(0))
kill_Time = datetime.datetime.now()
if tmp_killtime < kill_Time :
kill_Time = tmp_killtime + datetime.timedelta(days=int(1))
else:
kill_Time = tmp_killtime
for i in range(len(basicSetting)):
basicSetting[i] = basicSetting[i].strip()
try:
if basicSetting[6] != "":
basicSetting[6] = int(basicSetting[6])
if basicSetting[7] != "":
basicSetting[7] = int(basicSetting[7])
if basicSetting[8] != "":
basicSetting[8] = int(basicSetting[8])
if basicSetting[11] != "":
basicSetting[11] = int(basicSetting[11])
if basicSetting[18] != "":
basicSetting[18] = int(basicSetting[18])
if basicSetting[19] != "":
basicSetting[19] = int(basicSetting[19])
if basicSetting[20] != "":
basicSetting[20] = int(basicSetting[20])
except ValueError:
raise Exception("[test_setting.ini] 파일 양식을 확인하세요.")
tmp_now = datetime.datetime.now() + datetime.timedelta(hours = int(basicSetting[0]))
if int(basicSetting[13]) == 0 :
endTime = tmp_now.replace(hour=int(basicSetting[4]), minute=int(basicSetting[5]), second = int(0))
endTime = endTime + datetime.timedelta(days=int(1000))
else :
endTime = tmp_now.replace(hour=int(basicSetting[4]), minute=int(basicSetting[5]), second = int(0))
if endTime < tmp_now :
endTime = endTime + datetime.timedelta(days=int(basicSetting[13]))
bossNum = int(len(boss_inputData)/6)
fixed_bossNum = int(len(fixed_inputData)/6)
for i in range(bossNum):
tmp_bossData.append(boss_inputData[i*6:i*6+6])
for i in range(fixed_bossNum):
tmp_fixed_bossData.append(fixed_inputData[i*6:i*6+6])
for j in range(bossNum):
for i in range(len(tmp_bossData[j])):
tmp_bossData[j][i] = tmp_bossData[j][i].strip()
for j in range(fixed_bossNum):
for i in range(len(tmp_fixed_bossData[j])):
tmp_fixed_bossData[j][i] = tmp_fixed_bossData[j][i].strip()
tmp_boss_name_list : list = []
tmp_nick : list = []
############## 일반보스 정보 리스트 #####################
for j in range(bossNum):
tmp_nick = []
tmp_len = tmp_bossData[j][1].find(':')
tmp_boss_name_list = tmp_bossData[j][0][11:].split(", ")
f.append(tmp_boss_name_list[0]) #bossData[0] : 보스명
if len(tmp_boss_name_list) > 1:
for nick in tmp_boss_name_list[1:]:
tmp_nick.append(nick)
tmp_nick.append(convertToInitialLetters(nick))
boss_nick[tmp_boss_name_list[0]] = tmp_nick
f.append(tmp_bossData[j][1][10:tmp_len]) #bossData[1] : 시
f.append(tmp_bossData[j][2][13:]) #bossData[2] : 멍/미입력
f.append(tmp_bossData[j][3][20:]) #bossData[3] : 분전 알림멘트
f.append(tmp_bossData[j][4][13:]) #bossData[4] : 젠 알림멘트
f.append(tmp_bossData[j][1][tmp_len+1:]) #bossData[5] : 분
f.append('') #bossData[6] : 메세지
f.append(tmp_bossData[j][5][11:]) #bossData[8] : 멍체크시간종류
bossData.append(f)
f = []
bossTime.append(datetime.datetime.now()+datetime.timedelta(days=365, hours = int(basicSetting[0])))
tmp_bossTime.append(datetime.datetime.now()+datetime.timedelta(days=365, hours = int(basicSetting[0])))
bossTimeString.append('99:99:99')
bossDateString.append('9999-99-99')
tmp_bossTimeString.append('99:99:99')
tmp_bossDateString.append('9999-99-99')
bossFlag.append(False)
bossFlag0.append(False)
bossMungFlag.append(False)
bossMungCnt.append(0)
tmp_fixed_now = datetime.datetime.now() + datetime.timedelta(hours = int(basicSetting[0]))
############## 고정보스 정보 리스트 #####################
for j in range(fixed_bossNum):
try:
tmp_fixed_len = tmp_fixed_bossData[j][1].find(':')
tmp_fixedGen_len = tmp_fixed_bossData[j][2].find(':')
fb.append(tmp_fixed_bossData[j][0][11:]) #fixed_bossData[0] : 보스명
fb.append(tmp_fixed_bossData[j][1][11:tmp_fixed_len]) #fixed_bossData[1] : 시
fb.append(tmp_fixed_bossData[j][1][tmp_fixed_len+1:]) #fixed_bossData[2] : 분
fb.append(tmp_fixed_bossData[j][4][20:]) #fixed_bossData[3] : 분전 알림멘트
fb.append(tmp_fixed_bossData[j][5][13:]) #fixed_bossData[4] : 젠 알림멘트
fb.append(tmp_fixed_bossData[j][2][12:tmp_fixedGen_len]) #fixed_bossData[5] : 젠주기-시
fb.append(tmp_fixed_bossData[j][2][tmp_fixedGen_len+1:]) #fixed_bossData[6] : 젠주기-분
fb.append(tmp_fixed_bossData[j][3][12:16]) #fixed_bossData[7] : 시작일-년
fb.append(tmp_fixed_bossData[j][3][17:19]) #fixed_bossData[8] : 시작일-월
fb.append(tmp_fixed_bossData[j][3][20:22]) #fixed_bossData[9] : 시작일-일
fixed_bossData.append(fb)
fb = []
fixed_bossFlag.append(False)
fixed_bossFlag0.append(False)
fixed_bossTime.append(tmp_fixed_now.replace(year = int(fixed_bossData[j][7]), month = int(fixed_bossData[j][8]), day = int(fixed_bossData[j][9]), hour=int(fixed_bossData[j][1]), minute=int(fixed_bossData[j][2]), second = int(0)))
if fixed_bossTime[j] < tmp_fixed_now :
while fixed_bossTime[j] < tmp_fixed_now :
fixed_bossTime[j] = fixed_bossTime[j] + datetime.timedelta(hours=int(fixed_bossData[j][5]), minutes=int(fixed_bossData[j][6]), seconds = int(0))
if tmp_fixed_now + datetime.timedelta(minutes=int(basicSetting[1])) <= fixed_bossTime[j] < tmp_fixed_now + datetime.timedelta(minutes=int(basicSetting[3])):
fixed_bossFlag0[j] = True
if fixed_bossTime[j] < tmp_fixed_now + datetime.timedelta(minutes=int(basicSetting[1])):
fixed_bossFlag[j] = True
fixed_bossFlag0[j] = True
except:
raise Exception(f"[fixed_boss.ini] 파일 {tmp_fixed_bossData[j][0][11:]} 부분 양식을 확인하세요.")
################# 이모지 로드 ######################
emo_inidata = repo.get_contents("emoji.ini")
emoji_data1 = base64.b64decode(emo_inidata.content)
emoji_data1 = emoji_data1.decode('utf-8')
emo_inputData = emoji_data1.split('\n')
for i in range(len(emo_inputData)):
tmp_emo = emo_inputData[i][8:].rstrip('\r')
if tmp_emo != "":
tmp_racing_unit.append(tmp_emo)
################# 리젠보스 시간 정렬 ######################
regenData = []
regenTime = []
regenbossName = []
outputTimeHour = []
outputTimeMin = []
for i in range(bossNum):
if bossData[i][2] == "1":
f.append(bossData[i][0] + "R")
else:
f.append(bossData[i][0])
f.append(bossData[i][1] + bossData[i][5])
regenData.append(f)
regenTime.append(bossData[i][1] + bossData[i][5])
f = []
regenTime = sorted(list(set(regenTime)))
for j in range(len(regenTime)):
for i in range(len(regenData)):
if regenTime[j] == regenData[i][1] :
f.append(regenData[i][0])
regenbossName.append(f)
try:
outputTimeHour.append(int(regenTime[j][:2]))
outputTimeMin.append(int(regenTime[j][2:]))
except ValueError:
raise Exception(f"[boss.ini] 파일 {f} gentime을 확인하시기 바랍니다.")
f = []
regenembed = discord.Embed(
title='----- 보스별 리스폰 시간 -----',
description= ' ')
for i in range(len(regenTime)):
if outputTimeMin[i] == 0 :
regenembed.add_field(name=str(outputTimeHour[i]) + '시간', value= '```'+ ', '.join(map(str, sorted(regenbossName[i]))) + '```', inline=False)
else :
regenembed.add_field(name=str(outputTimeHour[i]) + '시간' + str(outputTimeMin[i]) + '분', value= '```' + ','.join(map(str, sorted(regenbossName[i]))) + '```', inline=False)
regenembed.set_footer(text = 'R : 멍 보스')
##########################################################
if basicSetting[10] !="":
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] #정산
credentials = ServiceAccountCredentials.from_json_keyfile_name(basicSetting[10], scope) #정산
init()
channel = ''
#mp3 파일 생성함수(gTTS 이용, 남성목소리)
async def MakeSound(saveSTR, filename):
if aws_key != "" and aws_secret_key != "":
polly = boto3.client("polly", aws_access_key_id = aws_key, aws_secret_access_key = aws_secret_key, region_name = "eu-west-1")
s = '<speak><prosody rate="' + str(95) + '%">' + saveSTR + '</prosody></speak>'
response = polly.synthesize_speech(
TextType = "ssml",
Text=s,
OutputFormat="mp3",
VoiceId="Seoyeon")
stream = response.get("AudioStream")
with open(f"./{filename}.mp3", "wb") as mp3file:
data = stream.read()
mp3file.write(data)
else:
tts = gTTS(saveSTR, lang = 'ko')
tts.save(f"./{filename}.wav")
#mp3 파일 재생함수
async def PlaySound(voiceclient, filename):
if basicSetting[21] != "1":
return
# source = discord.FFmpegPCMAudio(filename)
source = discord.FFmpegOpusAudio(filename)
try:
voiceclient.play(source)
except discord.errors.ClientException:
while voiceclient.is_playing():
await asyncio.sleep(1)
while voiceclient.is_playing():
await asyncio.sleep(1)
voiceclient.stop()
# source.cleanup()
return
#my_bot.db 저장하기
async def dbSave():
global bossData
global bossNum
global bossTime
global bossTimeString
global bossDateString
global bossMungFlag
global bossMungCnt
for i in range(bossNum):
for j in range(bossNum):
if bossTimeString[i] and bossTimeString[j] != '99:99:99':
if bossTimeString[i] == bossTimeString[j] and i != j:
tmp_time1 = bossTimeString[j][:6]
tmp_time2 = (int(bossTimeString[j][6:]) + 1)%100
if tmp_time2 < 10 :
tmp_time22 = '0' + str(tmp_time2)
elif tmp_time2 == 60 :
tmp_time22 = '00'
else :
tmp_time22 = str(tmp_time2)
bossTimeString[j] = tmp_time1 + tmp_time22
datelist1 = bossTime
datelist = list(set(datelist1))
information1 = '----- 보스탐 정보 -----\n'
for timestring in sorted(datelist):
for i in range(bossNum):
if timestring == bossTime[i]:
if bossTimeString[i] != '99:99:99' or bossMungFlag[i] == True :
if bossMungFlag[i] == True :
if bossData[i][2] == '0' :
information1 += ' - ' + bossData[i][0] + '(' + bossData[i][1] + '.' + bossData[i][5] + ') : ' + tmp_bossTime[i].strftime('%H:%M:%S') + ' @ ' + tmp_bossTime[i].strftime('%Y-%m-%d') + ' (미입력 ' + str(bossMungCnt[i]) + '회)' + ' * ' + bossData[i][6] + '\n'
else :
information1 += ' - ' + bossData[i][0] + '(' + bossData[i][1] + '.' + bossData[i][5] + ') : ' + tmp_bossTime[i].strftime('%H:%M:%S') + ' @ ' + tmp_bossTime[i].strftime('%Y-%m-%d') + ' (멍 ' + str(bossMungCnt[i]) + '회)' + ' * ' + bossData[i][6] + '\n'
else:
if bossData[i][2] == '0' :
information1 += ' - ' + bossData[i][0] + '(' + bossData[i][1] + '.' + bossData[i][5] + ') : ' + bossTimeString[i] + ' @ ' + bossDateString[i] + ' (미입력 ' + str(bossMungCnt[i]) + '회)' + ' * ' + bossData[i][6] + '\n'
else :
information1 += ' - ' + bossData[i][0] + '(' + bossData[i][1] + '.' + bossData[i][5] + ') : ' + bossTimeString[i] + ' @ ' + bossDateString[i] + ' (멍 ' + str(bossMungCnt[i]) + '회)' + ' * ' + bossData[i][6] + '\n'
try :
contents = repo.get_contents("my_bot.db")
repo.update_file(contents.path, "bossDB", information1, contents.sha)
except Exception as e :
print ('save error!!')
print(e.args[1]['message']) # output: This repository is empty.
errortime = datetime.datetime.now()
print (errortime)
pass
#my_bot.db 불러오기
async def dbLoad():
global LoadChk
contents1 = repo.get_contents("my_bot.db")
file_data = base64.b64decode(contents1.content)
file_data = file_data.decode('utf-8')
beforeBossData = file_data.split('\n')
if len(beforeBossData) > 1:
for i in range(len(beforeBossData)-1):
for j in range(bossNum):
startPos = beforeBossData[i+1].find('-')
endPos = beforeBossData[i+1].find('(')
if beforeBossData[i+1][startPos+2:endPos] == bossData[j][0] :
#if beforeBossData[i+1].find(bossData[j][0]) != -1 :
tmp_mungcnt = 0
tmp_len = beforeBossData[i+1].find(':')
tmp_datelen = beforeBossData[i+1].find('@')
tmp_msglen = beforeBossData[i+1].find('*')
years1 = beforeBossData[i+1][tmp_datelen+2:tmp_datelen+6]
months1 = beforeBossData[i+1][tmp_datelen+7:tmp_datelen+9]
days1 = beforeBossData[i+1][tmp_datelen+10:tmp_datelen+12]
hours1 = beforeBossData[i+1][tmp_len+2:tmp_len+4]
minutes1 = beforeBossData[i+1][tmp_len+5:tmp_len+7]
seconds1 = beforeBossData[i+1][tmp_len+8:tmp_len+10]
now2 = datetime.datetime.now() + datetime.timedelta(hours = int(basicSetting[0]))
tmp_now = datetime.datetime.now() + datetime.timedelta(hours = int(basicSetting[0]))
tmp_now = tmp_now.replace(year = int(years1), month = int(months1), day = int(days1), hour=int(hours1), minute=int(minutes1), second = int(seconds1))
if bossData[j][7] == "1":
tmp_now_chk = tmp_now + datetime.timedelta(minutes = int(basicSetting[2]))
else:
tmp_now_chk = tmp_now + datetime.timedelta(minutes = int(basicSetting[22]))
if tmp_now_chk < now2 :
deltaTime = datetime.timedelta(hours = int(bossData[j][1]), minutes = int(bossData[j][5]))
while tmp_now_chk < now2 :
tmp_now_chk = tmp_now_chk + deltaTime
tmp_now = tmp_now + deltaTime
tmp_mungcnt = tmp_mungcnt + 1
if tmp_now_chk > now2 > tmp_now: #젠중.
bossMungFlag[j] = True
tmp_bossTime[j] = tmp_now
tmp_bossTimeString[j] = tmp_bossTime[j].strftime('%H:%M:%S')
tmp_bossDateString[j] = tmp_bossTime[j].strftime('%Y-%m-%d')
bossTimeString[j] = '99:99:99'
bossDateString[j] = '9999-99-99'
bossTime[j] = tmp_bossTime[j] + datetime.timedelta(days=365)
else:
tmp_bossTime[j] = bossTime[j] = tmp_now
tmp_bossTimeString[j] = bossTimeString[j] = bossTime[j].strftime('%H:%M:%S')
tmp_bossDateString[j] = bossDateString[j] = bossTime[j].strftime('%Y-%m-%d')
if now2 + datetime.timedelta(minutes=int(basicSetting[1])) <= tmp_bossTime[j] < now2 + datetime.timedelta(minutes=int(basicSetting[3])):
bossFlag0[j] = True
if tmp_bossTime[j] < now2 + datetime.timedelta(minutes=int(basicSetting[1])):
bossFlag[j] = True
bossFlag0[j] = True
bossData[j][6] = beforeBossData[i+1][tmp_msglen+2:len(beforeBossData[i+1])]
if beforeBossData[i+1][tmp_msglen-4:tmp_msglen-3] != 0 and beforeBossData[i+1][tmp_msglen-5:tmp_msglen-4] == ' ':
bossMungCnt[j] = int(beforeBossData[i+1][tmp_msglen-4:tmp_msglen-3]) + tmp_mungcnt
elif beforeBossData[i+1][tmp_msglen-5:tmp_msglen-4] != ' ':
bossMungCnt[j] = int(beforeBossData[i+1][tmp_msglen-5:tmp_msglen-4] + beforeBossData[i+1][tmp_msglen-4:tmp_msglen-3]) + tmp_mungcnt
else:
bossMungCnt[j] = 0
global FixedBossDateData
global fixed_bossFlag
global fixed_bossFlag0
global fixed_bossTime
global fixed_bossData
FixedBossDateData = []
fixed_bossFlag = []
fixed_bossFlag0 = []
fixed_bossTime = []
fixed_bossData = []
tmp_fixed_bossData = []
fb = []
fixed_inidata = repo.get_contents("fixed_boss.ini")
file_data2 = base64.b64decode(fixed_inidata.content)
file_data2 = file_data2.decode('utf-8')
fixed_inputData = file_data2.split('\n')
for i in range(len(fixed_inputData)):
FixedBossDateData.append(fixed_inputData[i])
del(fixed_inputData[0])
for i in range(fixed_inputData.count('\r')):
fixed_inputData.remove('\r')
fixed_bossNum = int(len(fixed_inputData)/6)
for i in range(fixed_bossNum):
tmp_fixed_bossData.append(fixed_inputData[i*6:i*6+6])
for j in range(fixed_bossNum):
for i in range(len(tmp_fixed_bossData[j])):
tmp_fixed_bossData[j][i] = tmp_fixed_bossData[j][i].strip()
tmp_fixed_now = datetime.datetime.now() + datetime.timedelta(hours = int(basicSetting[0]))
############## 고정보스 정보 리스트 #####################
for j in range(fixed_bossNum):
try:
tmp_fixed_len = tmp_fixed_bossData[j][1].find(':')
tmp_fixedGen_len = tmp_fixed_bossData[j][2].find(':')
fb.append(tmp_fixed_bossData[j][0][11:]) #fixed_bossData[0] : 보스명
fb.append(tmp_fixed_bossData[j][1][11:tmp_fixed_len]) #fixed_bossData[1] : 시
fb.append(tmp_fixed_bossData[j][1][tmp_fixed_len+1:]) #fixed_bossData[2] : 분
fb.append(tmp_fixed_bossData[j][4][20:]) #fixed_bossData[3] : 분전 알림멘트
fb.append(tmp_fixed_bossData[j][5][13:]) #fixed_bossData[4] : 젠 알림멘트
fb.append(tmp_fixed_bossData[j][2][12:tmp_fixedGen_len]) #fixed_bossData[5] : 젠주기-시
fb.append(tmp_fixed_bossData[j][2][tmp_fixedGen_len+1:]) #fixed_bossData[6] : 젠주기-분
fb.append(tmp_fixed_bossData[j][3][12:16]) #fixed_bossData[7] : 시작일-년
fb.append(tmp_fixed_bossData[j][3][17:19]) #fixed_bossData[8] : 시작일-월
fb.append(tmp_fixed_bossData[j][3][20:22]) #fixed_bossData[9] : 시작일-일
fixed_bossData.append(fb)
fb = []
fixed_bossFlag.append(False)
fixed_bossFlag0.append(False)
fixed_bossTime.append(tmp_fixed_now.replace(year = int(fixed_bossData[j][7]), month = int(fixed_bossData[j][8]), day = int(fixed_bossData[j][9]), hour=int(fixed_bossData[j][1]), minute=int(fixed_bossData[j][2]), second = int(0)))
if fixed_bossTime[j] < tmp_fixed_now :
while fixed_bossTime[j] < tmp_fixed_now :
fixed_bossTime[j] = fixed_bossTime[j] + datetime.timedelta(hours=int(fixed_bossData[j][5]), minutes=int(fixed_bossData[j][6]), seconds = int(0))
if tmp_fixed_now + datetime.timedelta(minutes=int(basicSetting[1])) <= fixed_bossTime[j] < tmp_fixed_now + datetime.timedelta(minutes=int(basicSetting[3])):
fixed_bossFlag0[j] = True
if fixed_bossTime[j] < tmp_fixed_now + datetime.timedelta(minutes=int(basicSetting[1])):
fixed_bossFlag[j] = True
fixed_bossFlag0[j] = True
except:
raise Exception(f"[fixed_boss.ini] 파일 {tmp_fixed_bossData[j][0]} 부분 양식을 확인하세요.")
LoadChk = 0
print ("<불러오기 완료>")
else:
LoadChk = 1
print ("보스타임 정보가 없습니다.")
#고정보스 날짜저장
async def FixedBossDateSave():
global fixed_bossData
global fixed_bossTime
global fixed_bossNum
global FixedBossDateData
global indexFixedBossname
for i in range(fixed_bossNum):
FixedBossDateData[indexFixedBossname[i] + 3] = 'startDate = '+ fixed_bossTime[i].strftime('%Y-%m-%d') + '\n'
FixedBossDateDataSTR = ""
for j in range(len(FixedBossDateData)):
pos = len(FixedBossDateData[j])
tmpSTR = FixedBossDateData[j][:pos-1] + '\r\n'
FixedBossDateDataSTR += tmpSTR
contents = repo.get_contents("fixed_boss.ini")
repo.update_file(contents.path, "bossDB", FixedBossDateDataSTR, contents.sha)
#사다리함수
async def LadderFunc(number, ladderlist, channelVal):
result_ladder = random.sample(ladderlist, number)
lose_member = [item for item in ladderlist if item not in result_ladder]
result_ladderSTR = ','.join(map(str, result_ladder))
embed = discord.Embed(title = "🎲 사다리! 묻고 더블로 가!",color=0x00ff00)
embed.add_field(name = "👥 참가자", value = f"```fix\n{', '.join(ladderlist)}```", inline=False)
embed.add_field(name = "😍 당첨", value = f"```fix\n{', '.join(result_ladder)}```")
embed.add_field(name = "😭 낙첨", value = f"```{', '.join(lose_member)}```")
await channelVal.send(embed=embed, tts=False)
#data초기화
async def init_data_list(filename, first_line : str = "-----------"):
try :
contents = repo.get_contents(filename)
repo.update_file(contents.path, "deleted list " + str(filename), first_line, contents.sha)
print ('< 데이터 초기화 >')
except Exception as e :
print ('save error!!')
print(e.args[1]['message']) # output: This repository is empty.
errortime = datetime.datetime.now()
print (errortime)
pass
#data저장
async def data_list_Save(filename, first_line : str = "-----------", save_data : dict = {}):
output_list = first_line+ '\n'
for key, value in save_data.items():
output_list += str(key) + ' ' + str(value) + '\n'
try :
contents = repo.get_contents(filename)
repo.update_file(contents.path, "updated " + str(filename), output_list, contents.sha)
except Exception as e :
print ('save error!!')
print(e.args[1]['message']) # output: This repository is empty.
errortime = datetime.datetime.now()
print (errortime)
pass
#서버(길드) 정보
async def get_guild_channel_info(bot):
text_channel_name : list = []
text_channel_id : list = []
voice_channel_name : list = []
voice_channel_id : list = []
for guild in bot.guilds:
for text_channel in guild.text_channels:
text_channel_name.append(text_channel.name)
text_channel_id.append(str(text_channel.id))
for voice_channel in guild.voice_channels:
voice_channel_name.append(voice_channel.name)
voice_channel_id.append(str(voice_channel.id))
return text_channel_name, text_channel_id, voice_channel_name, voice_channel_id
class taskCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.checker = True
self.main_task.start()
@tasks.loop(seconds=1.0, count=1)
async def main_task(self):
boss_task = asyncio.get_event_loop().create_task(self.boss_check())
await boss_task
@main_task.before_loop
async def before_tast(self):
await self.bot.wait_until_ready()
################ 명존쎄 ################
@commands.command(name=command[8][0], aliases=command[8][1:])
async def command_task_list(self, ctx : commands.Context):
if ctx.message.channel.id != basicSetting[7]:
return
for t in asyncio.Task.all_tasks():
# print(t._coro.__name__)
if t._coro.__name__ == f"boss_check":
if t.done():
try:
t.exception()
except asyncio.CancelledError:
continue
continue
t.cancel()
# await ctx.send( '< 보탐봇 명치 맞고 숨 고르기 중! 잠시만요! >', tts=False)
try:
file = discord.File("./명치.JPG")
await ctx.send(file = file)
except:
await ctx.send( '< 보탐봇 명치 맞고 숨 고르기 중! 잠시만요! >', tts=False)
print("명치!")
await dbSave()
await data_list_Save("kill_list.ini", "-----척살명단-----", kill_Data)
await data_list_Save("item_list.ini", "-----아이템목록-----", item_Data)
for vc in self.bot.voice_clients:
if vc.guild.id == int(ctx.guild.id):
if vc.is_playing():
vc.stop()
await vc.disconnect(force=True)
if basicSetting[21] != "1":
print("명치복구완료!")
await dbLoad()
await self.bot.get_channel(channel).send( '< 다시 왔습니다!(보이스 미사용) >', tts=False)
self.checker = True
boss_task = asyncio.Task(self.boss_check())
return
async def boss_check(self):
await self.bot.wait_until_ready()
global channel
global endTime
global basicSetting
global bossData
global fixed_bossData
global bossNum
global fixed_bossNum
global chkvoicechannel
global chkrelogin
global bossTime
global tmp_bossTime
global fixed_bossTime
global bossTimeString
global bossDateString
global tmp_bossTimeString
global tmp_bossDateString
global bossFlag
global bossFlag0
global fixed_bossFlag
global fixed_bossFlag0
global bossMungFlag
global bossMungCnt
global channel_info
global channel_name
global channel_id
global channel_voice_name
global channel_voice_id
global channel_type
global endTime
global kill_Time
if chflg == 1 :
if len(self.bot.voice_clients) == 0 :
if basicSetting[21] == "1":
try:
await self.bot.get_channel(basicSetting[6]).connect(reconnect=True, timeout=5)
if self.bot.voice_clients[0].is_connected() :
await self.bot.get_channel(channel).send( '< 다시 왔습니다! >', tts=False)
self.checker = True
print("명치복구완료!")
except:
await self.bot.get_channel(channel).send( '< 음성채널 접속 에러! >', tts=False)
self.checker = False
print("명치복구실패!")
pass
await dbLoad()
while True:
############ 워닝잡자! ############
if log_stream.getvalue().find("Awaiting") != -1:
log_stream.truncate(0)
log_stream.seek(0)
await self.bot.get_channel(channel).send( '< 디코접속에러! 잠깐 나갔다 올께요! >', tts=False)
await dbSave()
break
log_stream.truncate(0)
log_stream.seek(0)
##################################