-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiscrod_bot.py
More file actions
1542 lines (1319 loc) · 74.2 KB
/
Copy pathdiscrod_bot.py
File metadata and controls
1542 lines (1319 loc) · 74.2 KB
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
import asyncio
import discord
import time
import random
import sqlite3
import hashlib
import os
import openpyxl
import ast
import re
# import gensim
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from discord.ui import Button, View
from discord import app_commands
from discord.ext import commands
from discord.utils import get
from discord.http import Route
from discord import Intents
from openpyxl.utils import get_column_letter
from openpyxl import Workbook, load_workbook
from discord.ext import tasks
from datetime import datetime
from sklearn.feature_extraction.text import CountVectorizer
from nltk import ngrams
# from gensim.models import Word2Vec
from collections import Counter
from collections import defaultdict
from sklearn.manifold import TSNE
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
class CostomCommandTree(app_commands.CommandTree):
def add_command(self, command, *args, override=True, **kwargs):
super().add_command(command, *args, override=override, **kwargs)
intents = discord.Intents.all()
intents.guilds = True
client = discord.Client(intents= intents)
openxl = openpyxl.load_workbook("discordbot.xlsx")
bot = commands.Bot(command_prefix='!',intents=intents, tree_cls=CostomCommandTree)
dt = datetime.now()
global preset
preset = 0
global start_time
start_time = None
# SQLite 데이터베이스 연결
conn = sqlite3.connect('conversation_data.db')
c = conn.cursor()
# 테이블 생성
c.execute('''
CREATE TABLE IF NOT EXISTS conversations
(id INTEGER PRIMARY KEY AUTOINCREMENT, word_index TEXT, introduction TEXT, i_bigrams TEXT, i_trigrams TEXT, answer TEXT, a_bigrams TEXT, a_trigrams TEXT)
''')
# FTS5 테이블 생성
c.execute("CREATE VIRTUAL TABLE IF NOT EXISTS wordserch USING fts5(word_index, content='conversations', content_rowid= 'id')")
# 트리거 생성
c.execute("""
CREATE TRIGGER IF NOT EXISTS fts_trigger AFTER INSERT ON conversations BEGIN
INSERT INTO wordserch (rowid, word_index)
VALUES (new.id, new.word_index);
END;
""")
c.execute("""
CREATE TRIGGER IF NOT EXISTS fts_delete_trigger AFTER DELETE ON conversations BEGIN
DELETE FROM wordserch WHERE rowid = old.id;
END;
""")
def sheetname(servername):
if servername in openxl.sheetnames:
if openxl.active.title != servername:
openxl.move_sheet(servername,0)
openxl.save('nemobot.xlsx')
return servername
elif servername not in openxl.sheetnames:
openxl.create_sheet('{}'.format(servername),0)
openxl.save('nemobot.xlsx')
return servername
def checkRow(ctx):
for row in range(1, openxl[sheetname(ctx)].max_row + 1):
if openxl[sheetname(ctx)].cell(row, 1).value is None or '':
break
return row +1
def checkCol(ctx):
for column in range(1, openxl[sheetname(ctx)].max_column+1):
if openxl[sheetname(ctx)].cell(1, column).value is None:
break
return column +1
def sheetsort(ctx):
sheet = openxl[sheetname(ctx)]
_row = checkRow(ctx)
_col = checkCol(ctx)
# 데이터 불러오기
data = []
for row_num in range(1, _row):
row_data = []
for col_num in range(1, _col):
cell_value = openxl[sheetname(ctx)].cell(row=row_num, column=col_num).value
if cell_value is not None:
row_data.append(cell_value)
data.append(row_data)
# B열 기준 내림차순 정렬
sorted_data = sorted(data, key=lambda x: x[1], reverse=True)
# 다시 셀에 입력
for row_idx, row_data in enumerate(sorted_data, start=1):
for col_idx, value in enumerate(row_data, start=1):
sheet.cell(row=row_idx, column=col_idx, value=value)
openxl.save("nemobot.xlsx")
def editbnr(ctx):
servername = sheetname(ctx.guild.name)
editbanner = discord.Embed(title="출석체크!",description="순위", colour=discord.Colour.blue())
editbanner.set_footer(text="출석하려면 버튼을 눌러주세요")
sheetsort(servername)#시트소팅
_row = checkRow(servername)
for row in range(1, _row):
value2 = "누적 {} 회 오늘은 {}\n마지막 출석 {}".format (openxl[servername].cell(row, 2).value, openxl[servername].cell(row, 3).value, openxl[servername].cell(row, 4).value)
editbanner.add_field(name=openxl[servername].cell(row, 1).value, value=value2, inline=False)
return editbanner
@bot.event
async def on_ready():
global bannersend
print('다음으로 로그인합니다: ')
print(bot.user.name)
print(client.shard_id)
print(client.application_id)
print('connection was succesful')
await bot.change_presence(status=discord.Status.online, activity=discord.Game("/명령어"))
for joiningguild in bot.guilds:
if f'{bot.user.name.replace(" ", "-").replace("(","-").replace(")","")}의-학습-허용' not in [channel.name for channel in joiningguild.text_channels]:
role = discord.utils.get(joiningguild.roles, name=bot.user.name)
overwrites = {
joiningguild.default_role: discord.PermissionOverwrite(send_messages=False),
role: discord.PermissionOverwrite(send_messages=True)
}
category = discord.utils.get(joiningguild.categories, name = bot.user.name)
print(f"debugging category: {category}")
if category:
pass
else:
await joiningguild.create_category(bot.user.name)
category = discord.utils.get(joiningguild.categories, name = bot.user.name)
if f'{bot.user.name.replace(" ", "-").replace("(","-").replace(")","")}의-학습-허용' not in [channel.name for channel in joiningguild.text_channels]:
await joiningguild.create_text_channel(f'{bot.user.name.replace(' ', '-').replace('(','-').replace(')','')}의-학습-허용', category = category, overwrites=overwrites, topic ="채팅학습 허용을 선택합니다")
print("bot is checking channel:")
for ch in joiningguild.text_channels:
print(ch.name)
if ch.name == f"{bot.user.name.replace(" ","-").replace("(","-").replace(")","")}출석체크방-beta":
target_message=await ch.history(limit=None).flatten()
print("bot is checking message:")
print([target_message])
await ch. delete_messages(target_message)
value1 ,value2 = await bannersendfnc(ch)
await ch.send("봇이 재연결되었습니다", delete_after = 2)
global bannersend
bannersend=await ch.send(embed=value1, view= value2)
break
else:
pass
while on_ready:
res = await bot.wait_for('interaction')
for item in [res.data]:
try:
if item['custom_id'] == 'checkbutton':
# 'checkbutton' 뒤의 문자열 추출
channel_name = item['custom_id'][len('checkbutton'):].strip("', ")
print("{}채널에서 버튼이 눌렸습니다".format(channel_name))
inputres = res
print(inputres)
await checkbutton_callback(inputres)
else:
print([res.data])
except:
pass
@bot.event
async def bannersendfnc(channel):
checkbutton = Button(label="출석확인", style=discord.ButtonStyle.green, custom_id= 'checkbutton')
view = View()
view.add_item(checkbutton)
es = discord.Embed(title="출석체크!",description="순위", colour=discord.Colour.blue())
es.set_footer(text="출석하려면 버튼을 눌러주세요")
ctx = channel.guild.name
servername = sheetname(ctx)
_row = checkRow(ctx)
for row in range(1, _row):
if openxl[servername].cell(row, 4).value != "{}년 {}월 {}일".format (datetime.now().year, datetime.now().month, datetime.now().day):
openxl[servername].cell(row= row, column=3, value = '출석안함')
for row in range(1, _row):
value2 = "누적 {} 회 오늘은 {}\n마지막 출석 {}".format (openxl[servername].cell(row, 2).value, openxl[servername].cell(row, 3).value, openxl[servername].cell(row, 4).value)
es.add_field(name=openxl[servername].cell(row, 1).value, value=value2, inline=False)
return es, view
@tasks.loop(seconds=10)
async def dailyset(ctx):
if (dt.hour == 0) and (dt.minute == 0) and (dt.second > 0):
servername = sheetname(ctx.guild.name)
_row=checkRow(servername)
for row in range(1, _row):
openxl[servername].cell(row=row, column=3,value='출석안함')
es = discord.Embed(title="출석체크!",description="순위", colour=discord.Colour.blue())
es.set_footer(text="출석하려면 버튼을 눌러주세요")
_row = checkRow(servername)
for row in range(1, _row):
value2 = "누적 {} 회 오늘은 {}\n마지막 출석 {}".format (openxl[servername].cell(row, 2).value, openxl[servername].cell(row, 3).value, openxl[servername].cell(row, 4).value)
es.add_field(name=openxl[servername].cell(row, 1).value, value=value2, inline=False)
for joiningguild in bot.guilds:
includech = joiningguild.text_channels
for ch in includech:
if ch.name == f"{bot.user.name.replace(" ","-").replace("(","-").replace(")","")}출석체크방-beta":
target_message=await ch.history(limit=1).flatten()
await target_message[0].edit(embed=es)
break
else:
return
else:
return
@bot.command()
async def role(ctx):
print(await ctx.guild.fetch_roles())
a = ctx.guild.get_member(bot.user.id).roles
await ctx.reply(f"제가 가진 역할은{a}")
@bot.command()
async def test1(ctx):
await ctx.reply(f"test 성공하셧네요",)
@bot.tree.command(name='test', description='testing tress command')
async def test(ctx):
await ctx.reply(f"test 성공하셧네요")
@app_commands.command()
async def fruits(interaction: discord.Interaction, fruit: str):
await interaction.response.send_message(f'Your favourite fruit seems to be {fruit}')
@fruits.autocomplete('fruit')
async def fruits_autocomplete(
interaction: discord.Interaction,
current: str,
) -> list[app_commands.Choice[str]]:
fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
return [
app_commands.Choice(name=fruit, value=fruit)
for fruit in fruits if current.lower() in fruit.lower()
]
@bot.command()
@commands.has_permissions(administrator = True)
async def removecommand(ctx, command):
for cmd in bot.walk_commands():
if cmd.name.lower() == command.lower():
bot.remove_command(cmd)
await ctx.message.add_reaction('✅')
return
await ctx.channel.send(f"Command `{command}` does not exist")
@bot.tree.command(name="setup",description="setup attendent")
async def setup(ctx):
servername = sheetname(ctx.guild.name)
if ctx.user.guild_permissions.administrator:
_row=checkRow(servername)
for row in range(1, _row):
openxl[servername].cell(row=row, column=3,value='출석안함')
sheetsort(servername)#시트소트
await ctx.reply("dailyset 출석안함 done")
es = discord.Embed(title="출석체크!",description="순위", colour=discord.Colour.blue())
es.set_footer(text="출석하려면 버튼을 눌러주세요")
_row = checkRow(servername)
for row in range(1, _row):
value2 = "누적 {} 회 오늘은 {}\n마지막 출석 {}".format (openxl[servername].cell(row, 2).value, openxl[servername].cell(row, 3).value, openxl[servername].cell(row, 4).value)
es.add_field(name=openxl[servername].cell(row, 1).value, value=value2, inline=False)
includech = ctx.guild.text_channels
for ch in includech:
if ch.name == f"{bot.user.name.replace(" ","-").replace("(","-").replace(")","")}출석체크방-beta":
target_message=await ch.history(limit=1).flatten()
await target_message[0].edit(embed=es)
break
else:
ctx.send("전용채널이 없습니다")
else:
ctx.reply("관리자 권한이 필요합니다",ephemeral=True)
@bot.tree.command(name="전용채널생성",description="전용채널을 생성합니다")
async def 전용채널생성(ctx):
if ctx.channel.name != f"{bot.user.name.replace(" ","-").replace("(","-").replace(")","")}출석체크방-beta" and ctx.user.guild_permissions.administrator:
role = discord.utils.get(ctx.guild.roles, name=bot.user.name)
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(send_messages=False),
role: discord.PermissionOverwrite(send_messages=True)
}
await ctx.reply("명령어 사용!")
if not f'{bot.user.name.replace(' ', '-').replace('(','-').replace(')','')}의-학습-허용' in ctx.guild.text_channels:
if not f'{bot.user.name}' in ctx.guild.categories:
await ctx.guild.create_category(bot.user.name)
else:
pass
category = discord.utils.get(ctx.guild.categories, name = bot.user.name)
await ctx.guild.create_text_channel(f'{bot.user.name.replace(' ', '-').replace('(','-').replace(')','')}의-학습-허용', category = category, overwrites=overwrites, topic ="채팅학습 허용을 선택합니다")
h = False
t = False
includech = ctx.guild.text_channels
for ch in includech:
if ch.name == f'{bot.user.name}출석체크방-beta':
await ctx.send(embed=discord.Embed(title="전용채널이 존재합니다",description=ch.name, color=0xff0000))
h = True
break
includect = ctx.guild.categories
for ct in includect:
if ct.name == bot.user.name:
await ctx.send(embed=discord.Embed(title="카테고리가 존재합니다",description=ct.name, color= 0xff0000))
t = True
break
if h == False and t == True:
category = discord.utils.get(ctx.guild.categories, name = bot.user.name)
await ctx.guild.create_text_channel(f'{bot.user.name}출석체크방-beta', category = category, overwrites=overwrites, topic ="출석체크방입니다\n(※알림 꺼두세요※)")
await ctx.send(embed=discord.Embed(title="채널을 생성했습니다",description=f"{bot.user.name.replace(" ","-").replace("(","-").replace(")","")}출석체크방-beta", color= 0xff000))
elif h == False and t == False:
await ctx.guild.create_category(bot.user.name)
category = discord.utils.get(ctx.guild.categories, name = bot.user.name)
await ctx.guild.create_text_channel(f'{bot.user.name}출석체크방-beta', category = category, overwrites=overwrites, topic ="출석체크방입니다\n(※알림 꺼두세요※)")
embed = discord.Embed(title = "채널 및 카테고리를 생성했습니다", color = 0xff000)
embed.add_field(name = "생성된 카테고리", value = "bot.user.name")
embed.add_field(name = "생성된 채널", value = f"{bot.user.name.replace(" ","-").replace("(","-").replace(")","")}출석체크방-beta")
await ctx.send(embed = embed)
elif h == True and t == False:
ch = discord.utils.get(ctx.guild.channels, name = f'{bot.user.name}출석체크방-beta')
await ch.delete()
category = await ctx.guild.create_category(bot.user.name)
await ctx.guild.create_text_channel(f'{bot.user.name}출석체크방-beta', category = category, overwrites=overwrites, topic ="출석체크방입니다n(※알림 꺼두세요※)")
await ctx.send(embed=discord.Embed(title="투표 채널을 초기화하고 카테고리를 생성했습니다",description="bot.user.name", color= 0xffff00))
elif h == True and t == True:
ch = discord.utils.get(ctx.guild.channels, name = f'{bot.user.name}출석체크방-beta')
await ch.delete()
category = discord.utils.get(ctx.guild.categories, name = bot.user.name)
await ctx.guild.create_text_channel(f'{bot.user.name}출석체크방-beta', category = category, overwrites=overwrites, topic ="출석체크방입니다\n(※알림 꺼두세요※)")
await ctx.send(embed=discord.Embed(title="투표채널을 초기화하였습니다",description=f"{bot.user.name.replace(" ","-").replace("(","-").replace(")","")}출석체크방-beta", color= 0xffff00))
await ctx.send("투표가 생성되니다")
await ctx.send("투표가 생성된 방의 알림을 꺼주세요")
elif ctx.user.guild_permissions.administrator is False:
await ctx.reply("관리자가 아닙니다",ephemeral=True)
else:
await ctx.reply("현재 카테고리 제외 다른 채널에 입력해주세요",ephemeral=True)
@bot.tree.command(name="전용채널삭제",description="전용채널을 삭제합니다")
async def 전용채널삭제(ctx):
if ctx.channel.name != f"{bot.user.name.replace(" ","-").replace("(","-").replace(")","")}출석체크방-beta" and ctx.user.guild_permissions.administrator:
await ctx.reply("명령어 사용!")
d = 0
includedch = ctx.guild.text_channels
for ch in includedch:
if ch.name == f'{bot.user.name}출석체크방-beta':
deletech = discord.utils.get(ctx.guild.channels, name = f'{bot.user.name}출석체크방-beta')
await deletech.delete()
await ctx.send(embed=discord.Embed (title="채널삭제됨",description=ch.name, color= 0xffff00))
d=1
includedct = ctx.guild.categories
for ct in includedct:
if ct.name == bot.user.name:
deletect = discord.utils.get(ctx.guild.categories, name = bot.user.name)
await deletect.delete()
await ctx.send(embed=discord.Embed (title="카테고리 삭제됨",description=ct.name, color= 0xffff00))
d=1
if d==0:
await ctx.send(embed=discord.Embed (title="삭제할 채널 혹은 카테고리가 존재하지 않습니다",color= 0xff0000))
elif ctx.channel.name != f"{bot.user.name.replace(" ","-").replace("(","-").replace(")","")}출석체크방-beta" and ctx.user.guild_permissions.administrator is False:
ctx.reply("관리자 권한이 필요합니다",ephemeral=True)
else:
await ctx.send("현재 카테고리를 제외한 다른 채널에 입력해주세요",ephemeral=True)
@bot.event
async def on_guild_join(guild):
h = False
t = False
role = discord.utils.get(guild.roles, name=bot.user.name)
overwrites = {
guild.default_role: discord.PermissionOverwrite(send_messages=False),
role: discord.PermissionOverwrite(send_messages=True)
}
includech = guild.text_channels
for ch in includech:
if ch.name == f'{bot.user.name}출석체크방-beta':
h = True
break
includect = guild.categories
for ct in includect:
if ct.name == bot.user.name:
t = True
break
if h == False and t == True:
category = discord.utils.get(guild.categories, name = bot.user.name)
await guild.create_text_channel(f'{bot.user.name}출석체크방-beta', category = category, overwrites=overwrites, topic ="출석체크방입니다\n(※알림 꺼두세요※)")
elif h == False and t == False:
await guild.create_category(bot.user.name)
category = discord.utils.get(guild.categories, name = bot.user.name)
await guild.create_text_channel(f'{bot.user.name}출석체크방-beta', category = category, overwrites=overwrites, topic ="출석체크방입니다\n(※알림 꺼두세요※)")
elif h == True and t == False:
ch = discord.utils.get(guild.channels, name = f'{bot.user.name}출석체크방-beta')
await ch.delete()
category = await guild.create_category(bot.user.name)
await guild.create_text_channel(f'{bot.user.name}출석체크방-beta', category = category, overwrites=overwrites, topic ="출석체크방입니다\n(※알림 꺼두세요※)")
elif h == True and t == True:
ch = discord.utils.get(guild.channels, name = f'{bot.user.name}출석체크방-beta')
await ch.delete()
category = discord.utils.get(guild.categories, name = bot.user.name)
await guild.create_text_channel(f'{bot.user.name}출석체크방-beta', category = category, overwrites=overwrites, topic ="출석체크방입니다\n(※알림 꺼두세요※)")
category = discord.utils.get(guild.categories, name = bot.user.name)
if not f'{bot.user.name.replace(' ', '-').replace('(','-').replace(')','')}의-학습-허용' in includech:
await guild.create_text_channel(f'{bot.user.name.replace(' ', '-').replace('(','-').replace(')','')}의-학습-허용', category = category, overwrites=overwrites, topic ="채팅학습 허용을 선택합니다")
@bot.event
async def on_guild_channel_create(channel):
ctx=channel.guild
if channel.name==f"{bot.user.name.replace(" ","-").replace("(","-").replace(")","")}출석체크방-beta":
value1,value2 = await bannersendfnc(channel)
global bannersend
bannersend= await channel.send(embed=value1, view= value2)
dailyset.start(ctx)
if channel.name == f'{bot.user.name.replace(' ', '-').replace('(','-').replace(')','')}의-학습-허용':
image = discord.File("attendencecheckbot(ai).png", filename="ailogo.png")
allowembed = discord.Embed(title="현재 해당 봇이 자신의 채팅을 학습하는데 동의하면 아래 ✅에 체크해주세요", description="동의에 체크된 사람의 채팅만 학습하며 체크를 해제할 시 해당 사용자의 채팅 학습을 중단합니다", color=0x00ff56)
allowembed.set_thumbnail(url="attachment://ailogo.png")
allowembed.add_field(name="-유의사항-", value= "1. 체크를 해제할 시 이전에 학습한 내용은 삭제되지 않습니다\n2. ✅에 확인되어있는 동안의 채팅만 학습됩니다\n3. 텍스트채팅만 학습하며 해당 봇의 학습이외의 목적으로 사용되지 않습니다 \n4.해당 모델은 디스코드에서 허용된 채팅으로만 데이터를 수집합니다", inline=True)
permitioncheck = await channel.send(embed=allowembed, file=image)
await permitioncheck.add_reaction('✅')
togletag = None
convtrance = False
needsetup = False
def is_introduction(tag):
global togletag, convtrance, conversations , needsetup
needsetup = False
# print(f"togletag: {togletag}")
if convtrance == False:
if togletag == tag or togletag == None:
togletag = tag
# print("1")
return 'introduction'
else: #togletag != tag
togletag = tag
convtrance = True
# print("2")
return 'answer'
elif convtrance == True:
if togletag == tag:
# print("3")
return 'answer'
else: #togletag != tag
convtrance = False
togletag = tag
needsetup = True
print("4, needsetup is true now")
return 'introduction'
def calculate_freq(raw_message):
words = raw_message.split()
# 단어, 바이그램, 트라이그램 빈도 업데이트
word_freq = dict(Counter(words))
# bi-gram 생성 및 빈도 계산
bigrams = list(ngrams(words, 2)) if len(words) >= 2 else []
bigram_freq = dict(Counter(bigrams))
# tri-gram 생성 및 빈도 계산
trigrams = list(ngrams(words, 3)) if len(words) >= 3 else []
trigram_freq = dict(Counter(trigrams))
# print(word_freq, bigram_freq, trigram_freq)
return word_freq, bigram_freq, trigram_freq
def handle_none(value):
return '' if value is None else value
conversations = defaultdict(lambda: {"introduction": [], "answer": []})
def save_data(tag, message):
global conversations, word_freq, bigram_freq, trigram_freq, needsetup, channel_id
conversationident = is_introduction(tag)
if needsetup == True:
raw_intoduction = ' '.join([m['raw_message'] for m in conversations['currunt_conversation']["introduction"]])
word_freq, bigram_freq, trigram_freq = calculate_freq(raw_intoduction)
conversations['currunt_conversation']['introduction'].append({"words": word_freq, "Bi-grams": bigram_freq, "Tri-grams": trigram_freq})
raw_answer = ' '.join([m['raw_message'] for m in conversations['currunt_conversation']["answer"]])
word_freq, bigram_freq, trigram_freq = calculate_freq(raw_answer)
conversations['currunt_conversation']['answer'].append({"words": word_freq, "Bi-grams": bigram_freq, "Tri-grams": trigram_freq})
# print(f"final conversation is : {conversations}")
introduction = conversations['currunt_conversation']["introduction"][1]['words']
i_bigrams = conversations['currunt_conversation']["introduction"][1]['Bi-grams']
i_trigrams = conversations['currunt_conversation']["introduction"][1]['Tri-grams']
answer = conversations['currunt_conversation']["answer"][1]['words']
a_bigrams = conversations['currunt_conversation']["answer"][1]['Bi-grams']
a_trigrams = conversations['currunt_conversation']["answer"][1]['Tri-grams']
# print(f"this is the final conversation data: {conversations}")
# introduction과 answer의 단어들을 문자열로 변환
introduction_str = ' '.join(conversations['currunt_conversation']["introduction"][1]['words'])
answer_str = ' '.join(conversations['currunt_conversation']["answer"][1]['words'])
word_index = introduction_str + ' ' + answer_str
# 단어 검색 및 id 반환
targetserch = re.sub(r'\W+', ' ', word_index)
targets = targetserch.split()
# print(f"targets: {targets}")
datanotfound = None
all_ids = []
candidates = {}
for target in targets:
# print(f"target: {target}")
c.execute(f"SELECT rowid FROM wordserch WHERE word_index MATCH '{target}'")
ids = c.fetchall()
ids = [id[0] for id in ids]
all_ids.extend(ids)
all_ids = list(set(all_ids))
if len(all_ids)==0:
if datanotfound == None:
datanotfound = True
else:
datanotfound = True
else:
datanotfound = False
# 해당하는 항목이 있다면 기존 항목 수정
for id in all_ids:
c.execute(f"SELECT * FROM conversations WHERE id = '{id}'")
id_data = c.fetchone()
# print(f"id row data: {id_data}")
candidate = {}
candidate['id'], candidate['word_index'], candidate['introduction'], candidate['i_bigrams'], candidate['i_trigrams'], candidate['answer'], candidate['a_bigrams'], candidate['a_trigrams'] = id_data
# candidate 딕셔너리의 데이터를 str -> ast로 변환
candidate_i_bigrams = ast.literal_eval(candidate['i_bigrams'])
candidate_i_trigrams = ast.literal_eval(candidate['i_trigrams'])
candidate_a_bigrams = ast.literal_eval(candidate['a_bigrams'])
candidate_a_trigrams = ast.literal_eval(candidate['a_trigrams'])
candidate_introduction = ast.literal_eval(candidate['introduction'])
candidate_answer = ast.literal_eval(candidate['answer'])
new_i_bigrams = ast.literal_eval(str(i_bigrams))
new_i_trigrams = ast.literal_eval(str(i_bigrams))
new_a_bigrams = ast.literal_eval(str(a_bigrams))
new_a_trigrams = ast.literal_eval(str(a_trigrams))
new_introduction = ast.literal_eval(str(introduction))
new_answer = ast.literal_eval(str(answer))
trigrampass = True
bigrampass = True
# trigram 확인
if set(new_i_trigrams.keys()).intersection(set(candidate_i_trigrams.keys())):
# 워드
for word, count in new_introduction.items():
if word in candidate_introduction:
candidate_introduction[word] += count
else:
candidate_introduction[word] = count
# 바이그램
for bigram, count in new_i_bigrams.items():
if bigram in candidate_i_bigrams:
candidate_i_bigrams[bigram] += count
else:
candidate_i_bigrams[bigram] = count
#트라이그램
for trigram, count in new_i_trigrams.items():
if trigram in candidate_i_trigrams:
candidate_i_trigrams[trigram] += count
else:
candidate_i_trigrams[trigram] = count
trigrampass = False
# print("found introduction matching whith introduction data at trigram")
if set(new_a_trigrams.keys()).intersection(set(candidate_i_trigrams.keys())):
#워드
for word, count in new_answer.items():
if word in candidate_introduction:
candidate_introduction[word] += count
else:
candidate_introduction[word] = count
# 바이그램
for bigram, count in new_a_bigrams.items():
if bigram in candidate_i_bigrams:
candidate_i_bigrams[bigram] += count
else:
candidate_i_bigrams[bigram] = count
# 트라이그램
for trigram, count in new_a_trigrams.items():
if trigram in candidate_i_trigrams:
candidate_i_trigrams[trigram] += count
else:
candidate_i_trigrams[trigram] = count
trigrampass = False
# print("found answer matching with introduction data as trigram")
if set(new_i_trigrams.keys()).intersection(set(candidate_a_trigrams.keys())):
# 워드
for word, count in new_introduction.items():
if word in candidate_answer:
candidate_answer[word] += count
else:
candidate_answer[word] = count
# 바이그램
for bigram, count in new_i_bigrams.items():
if bigram in candidate_a_bigrams:
candidate_a_bigrams[bigram] += count
else:
candidate_a_bigrams[bigram] = count
#트라이그램
for trigram, count in new_i_trigrams.items():
if trigram in candidate_a_trigrams:
candidate_a_trigrams[trigram] += count
else:
candidate_a_trigrams[trigram] = count
trigrampass = False
# print("found introduction matching whith answer data at trigram")
if set(new_a_trigrams.keys()).intersection(set(candidate_a_trigrams.keys())):
# 워드
for word, count in new_answer.items():
if word in candidate_answer:
candidate_answer[word] += count
else:
candidate_answer[word] = count
# 바이그램
for bigram, count in new_a_bigrams.items():
if bigram in candidate_a_bigrams:
candidate_a_bigrams[bigram] += count
else:
candidate_a_bigrams[bigram] = count
#트라이그램
for trigram, count in new_a_trigrams.items():
if trigram in candidate_a_trigrams:
candidate_a_trigrams[trigram] += count
else:
candidate_a_trigrams[trigram] = count
trigrampass = False
# print("found answer matching whith answer data at trigram")
# bigram 확인
if trigrampass == True:
if set(new_i_bigrams.keys()).intersection(set(candidate_i_bigrams.keys())):
# 워드
for word, count in new_introduction.items():
if word in candidate_introduction:
candidate_introduction[word] += count
else:
candidate_introduction[word] = count
# 바이그램
for bigram, count in new_i_bigrams.items():
if bigram in candidate_i_bigrams:
candidate_i_bigrams[bigram] += count
else:
candidate_i_bigrams[bigram] = count
#트라이그램
for trigram, count in new_i_trigrams.items():
if trigram in candidate_i_trigrams:
candidate_i_trigrams[trigram] += count
else:
candidate_i_trigrams[trigram] = count
bigrampass = False
# print("found introduction matching whith introduction data at bigram")
if set(new_a_bigrams.keys()).intersection(set(candidate_i_bigrams.keys())):
#워드
for word, count in new_answer.items():
if word in candidate_introduction:
candidate_introduction[word] += count
else:
candidate_introduction[word] = count
# 바이그램
for bigram, count in new_a_bigrams.items():
if bigram in candidate_i_bigrams:
candidate_i_bigrams[bigram] += count
else:
candidate_i_bigrams[bigram] = count
# 트라이그램
for trigram, count in new_a_trigrams.items():
if trigram in candidate_i_trigrams:
candidate_i_trigrams[trigram] += count
else:
candidate_i_trigrams[trigram] = count
bigrampass = False
# print("found answer matching with introduction data as bigram")
if set(new_i_bigrams.keys()).intersection(set(candidate_a_bigrams.keys())):
# 워드
for word, count in new_introduction.items():
if word in candidate_answer:
candidate_answer[word] += count
else:
candidate_answer[word] = count
# 바이그램
for bigram, count in new_i_bigrams.items():
if bigram in candidate_a_bigrams:
candidate_a_bigrams[bigram] += count
else:
candidate_a_bigrams[bigram] = count
#트라이그램
for trigram, count in new_i_trigrams.items():
if trigram in candidate_a_trigrams:
candidate_a_trigrams[trigram] += count
else:
candidate_a_trigrams[trigram] = count
bigrampass = False
# print("found introduction matching whith answer data at bigram")
if set(new_a_bigrams.keys()).intersection(set(candidate_a_bigrams.keys())):
# 워드
for word, count in new_answer.items():
if word in candidate_answer:
candidate_answer[word] += count
else:
candidate_answer[word] = count
# 바이그램
for bigram, count in new_a_bigrams.items():
if bigram in candidate_a_bigrams:
candidate_a_bigrams[bigram] += count
else:
candidate_a_bigrams[bigram] = count
#트라이그램
for trigram, count in new_a_trigrams.items():
if trigram in candidate_a_trigrams:
candidate_a_trigrams[trigram] += count
else:
candidate_a_trigrams[trigram] = count
bigrampass = False
# print("found answer matching with answer data at bigram")
# 단어 확인
if bigrampass == True:
if set(introduction_str.split()).intersection(candidate_introduction):
# 워드
for word, count in new_introduction.items():
if word in candidate_introduction:
candidate_introduction[word] += count
else:
candidate_introduction[word] = count
# 바이그램
for bigram, count in new_i_bigrams.items():
if bigram in candidate_i_bigrams:
candidate_i_bigrams[bigram] += count
else:
candidate_i_bigrams[bigram] = count
#트라이그램
for trigram, count in new_i_trigrams.items():
if trigram in candidate_i_trigrams:
candidate_i_trigrams[trigram] += count
else:
candidate_i_trigrams[trigram] = count
# print("found introduction matching whith introduction data at words")
if set(answer_str.split()).intersection(candidate_introduction):
#워드
for word, count in new_answer.items():
if word in candidate_introduction:
candidate_introduction[word] += count
else:
candidate_introduction[word] = count
# 바이그램
for bigram, count in new_a_bigrams.items():
if bigram in candidate_i_bigrams:
candidate_i_bigrams[bigram] += count
else:
candidate_i_bigrams[bigram] = count
# 트라이그램
for trigram, count in new_a_trigrams.items():
if trigram in candidate_i_trigrams:
candidate_i_trigrams[trigram] += count
else:
candidate_i_trigrams[trigram] = count
# print("found answer matching with introduction data as words")
if set(introduction_str.split()).intersection(candidate_answer):
# 워드
for word, count in new_introduction.items():
if word in candidate_answer:
candidate_answer[word] += count
else:
candidate_answer[word] = count
# 바이그램
for bigram, count in new_i_bigrams.items():
if bigram in candidate_a_bigrams:
candidate_a_bigrams[bigram] += count
else:
candidate_a_bigrams[bigram] = count
#트라이그램
for trigram, count in new_i_trigrams.items():
if trigram in candidate_a_trigrams:
candidate_a_trigrams[trigram] += count
else:
candidate_a_trigrams[trigram] = count
# print("found introduction matching whith answer data at words")
if set(answer_str.split()).intersection(candidate_answer):
for word, count in new_answer.items():
if word in candidate_answer:
candidate_answer[word] += count
else:
candidate_answer[word] = count
# 바이그램
for bigram, count in new_a_bigrams.items():
if bigram in candidate_a_bigrams:
candidate_a_bigrams[bigram] += count
else:
candidate_a_bigrams[bigram] = count
#트라이그램
for trigram, count in new_a_trigrams.items():
if trigram in candidate_a_trigrams:
candidate_a_trigrams[trigram] += count
else:
candidate_a_trigrams[trigram] = count
# print("found answer matching with answer data at words")
# 딕셔너리 리스트
dicts = [candidate_i_bigrams, candidate_i_trigrams, candidate_a_bigrams, candidate_a_trigrams]
# 키 튜플의 모든 요소를 리스트로 만들기
words_in_common = [item for dict_example in dicts for key in dict_example.keys() for item in key]
# targets와 word_index 사이 차집합 계산
word_index_set = set(candidate['word_index'].split())
targets_set = set(targets)
commonword = set(words_in_common)
new_words = targets_set.intersection(commonword) - word_index_set
# 새로운 단어를 word_index에 추가
candidate['word_index'] += ' ' + ' '.join(new_words)
candidate['i_bigrams'] = str(candidate_i_bigrams)
candidate['i_trigrams'] = str(candidate_i_trigrams)
candidate['a_bigrams'] = str(candidate_a_bigrams)
candidate['a_trigrams'] = str(candidate_a_trigrams)
candidate['introduction'] = str(candidate_introduction)
candidate['answer'] = str(candidate_answer)
# print(f"candidate: {candidate}")
# 딕셔너리 저장
print(f"candidateid:{candidate["id"]}")
candidates[candidate['id']] = candidate
# print(f"candidates: {candidates}")
for kid in candidates.keys():
# print(kid)
c.execute(f"""
UPDATE conversations
SET word_index = ?, introduction = ?, i_bigrams = ?, i_trigrams = ?, answer = ?, a_bigrams = ?, a_trigrams = ?
WHERE id = '{kid}'
""", (candidate['word_index'], candidate['introduction'], candidate['i_bigrams'], candidate['i_trigrams'], candidate['answer'], candidate['a_bigrams'], candidate['a_trigrams']))
conn.commit()
if datanotfound == True:
# 해당하는 항목이 없을시 새로울 항목으로 추가
c.execute("INSERT INTO conversations (word_index, introduction, i_bigrams, i_trigrams, answer, a_bigrams, a_trigrams) VALUES (?, ?, ?, ?, ?, ?, ?)",
(word_index, str(introduction), str(i_bigrams), str(i_trigrams), str(answer), str(a_bigrams), str(a_trigrams)))
conn.commit
else:
pass
# 변경 사항 커밋
# 데이터 삽입
conn.commit()
conversations = defaultdict(lambda: {"introduction": [], "answer": []})
# raw_message를 계속 이어붙임
if len(conversations['currunt_conversation'][f"{conversationident}"]) > 0:
conversations['currunt_conversation'][f"{conversationident}"][-1]['raw_message'] += ' ' + message
# print(conversations)
else:
conversations['currunt_conversation'][f"{conversationident}"].append({"raw_message": message})
print(f"cnversations: {conversations}")
@bot.event
async def on_message(ctx):
# # print([ctx])
# print(ctx.content)
# print([ctx.type])
if(ctx.type[1] == 0 and len(ctx.content)>0 and ctx.author.bot != True and (ctx.content[0].isalnum() or ctx.content[0] == '.') and not ctx.mentions and not 'http://' in ctx.content and not 'https://' in ctx.content):
if random.randrange(1,101) == 7:
# urllib.request.urlretrieve("https://www", ".png")
image = discord.File("gotcha1.png", filename="gotcha.png")
embed = discord.Embed(title="**당신의 메세지는 1%의 확률을 뚫고 봇의 가챠본능 이스터에그를 확인했습니다**", description="보상으로 가챠코드를 보여드리죠", color=0x00ff56)
embed.set_image(url="attachment://gotcha.png")
embed.add_field(name="굉장하군요", value= "축하드립니다", inline=True)
await ctx.reply(embed=embed, file=image)
sentence = ctx.content
tag = hashlib.md5(str(ctx.author.id).encode()).hexdigest() # ID 생성
targetch = discord.utils.get(ctx.guild.channels, name = f"{bot.user.name.replace(" ","-").replace("(","-").replace(")","")}의-학습-허용")
if targetch:
async for message in targetch.history():
if message.author.id == bot.user.id:
for reaction in message.reactions:
if str(reaction.emoji) == '✅':
# 학습 확인 사용자 가져옴
users = [user.id async for user in reaction.users()]
if ctx.author.id in users:
print("saving data")
save_data(tag, sentence)
else:
print("cannotuse data")
save_data(tag, "")
elif ctx.author.id == bot.user.id:
tag = hashlib.md5(str(ctx.author.id).encode()).hexdigest() # ID 생성
save_data(tag, ctx.content)
model_path = "chat model"
if os.path.isfile(model_path):
pass
# model = gensim.models.Word2Vec.load(model_path)
mention = [member.id for member in ctx.mentions]
if (random.randrange(1,2) == 1 or (bot.user.id in mention)) and os.path.isfile(model_path) and ctx.type[1] == 0 and ctx.author.bot != True and (ctx.content[0].isalnum() or ctx.content[0] == '.' or ctx.content[0] == '@') and not 'http://' in ctx.content and not 'https://' in ctx.content:
print("generating answer")
word_dict, bigram_dict, trigram_dict = calculate_freq(re.sub(r'\W+', ' ', ctx.content))
word_list = list(word_dict.keys())
bigram_list = list(bigram_dict.keys())
trigram_list = list(trigram_dict.keys())