-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
1311 lines (1246 loc) · 62.2 KB
/
bot.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
import asyncio
import configparser
import datetime
import json
import logging
import os
import random
import re
import shutil
import string
import sys
import time
import traceback
import discord
import nest_asyncio
import requests
import pickle
from discord.commands import Option
from discord.ext import commands, tasks, bridge
from discord.ui import Button, InputText, Modal, Select, View
from gtts import gTTS, lang, gTTSError
nest_asyncio.apply()
if os.name == 'nt':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
intents = discord.Intents.default()
intents.message_content = True
bot = bridge.Bot(
command_prefix=commands.when_mentioned,
description="A bot to convert text to speech in a voice channel using Google TTS APIs.",
intents=intents,
auto_sync_commands=True,
activity=discord.Game(name="Loading..."),
)
bot_version = "v3.6.4"
# --------------------------------------------------
# Folders
# --------------------------------------------------
root = os.path.dirname(os.path.abspath(__file__))
temp = os.path.join(os.path.dirname(os.path.abspath(__file__)),'temp')
configs = os.path.join(os.path.dirname(os.path.abspath(__file__)),'configs')
langfolder = os.path.join(os.path.dirname(os.path.abspath(__file__)),'lang')
# --------------------------------------------------
# Variables
# --------------------------------------------------
supported_languages_message = ""
lang_list = []
allroles = []
installed_langs = []
conf = {'role': 'TTS', 'lang': 'en', 'autosaychan': '[]', 'defvoice': 'en', 'silenceupdates': 'False', 'updateschannel': 'system', 'multiuser': 'True', 'usenicknames': 'False'}
punctuation = ['!', '"', '#', '$', '%', '&', "'", '*', '+', '-', '.', ',', ':', ';', '=', '?', '[', ']', '^', '_', '|', '~']
TOKEN = ""
# --------------------------------------------------
# Internal functions
# --------------------------------------------------
def generate_random_code():
return ''.join(random.choice(string.ascii_letters + string.digits) for i in range(1,9))
async def check_installed_languages():
global installed_langs
for lang in os.listdir(langfolder):
installed_langs.append(lang)
def return_language_string(lang, string):
global langfolder
config = configparser.ConfigParser()
if not os.path.exists(os.path.join(langfolder, lang)):
print(f"-> Language '{lang}' not found, defaulting to 'en'")
lang = "en"
config.read(os.path.join(langfolder, lang), encoding='utf-8')
try:
config['DEFAULT']
config['DEFAULT'][string].isspace()
except KeyError:
print(f"-> String '{string}' not found in language '{lang}', defaulting to 'en'")
lang = "en"
config.read(os.path.join(langfolder, lang), encoding='utf-8')
return config['DEFAULT'][string]
return config['DEFAULT'][string]
def get_guild_language(ctx, string):
config = configparser.ConfigParser()
try:
config.read(os.path.join(configs, str(ctx.guild.id)), encoding='utf-8')
except:
config.read(os.path.join(configs, str(ctx.id)), encoding='utf-8')
return return_language_string(config['DEFAULT']['lang'], string)
def showlangs(ctx: discord.AutocompleteContext):
global lang_list
return [lang for lang in lang_list if lang.startswith(ctx.value.lower())]
async def loadroles(bot):
global allroles
for guild in bot.guilds:
config = configparser.ConfigParser()
config.read(os.path.join(configs, str(guild.id)), encoding='utf-8')
if not discord.utils.get(guild.roles, name=config['DEFAULT']['role']):
try:
await guild.create_role(name=config['DEFAULT']['role'])
print(f"-> Role '{config['DEFAULT']['role']}' created in {guild.name}")
except:
print(f"-> Role '{config['DEFAULT']['role']}' could not be created in {guild.name}")
else:
print(f"-> Role '{config['DEFAULT']['role']}' found in {guild.name}")
allroles.append(config['DEFAULT']['role'])
allroles = list(dict.fromkeys(allroles))
def resettimer(guild):
config = configparser.ConfigParser()
config['DEFAULT'] = {'time': time.time()}
with open(os.path.join(temp, str(guild.id),'.clock'), 'w') as configfile:
config.write(configfile)
async def check_role(ctx):
config = configparser.ConfigParser()
config.read(os.path.join(configs, str(ctx.guild.id)), encoding='utf-8')
try:
rolename = config['DEFAULT']['role']
except KeyError:
config['DEFAULT']['role'] = conf['role']
try:
role = discord.utils.get(ctx.guild.roles, name=rolename)
except:
config = configparser.ConfigParser()
config.read(os.path.join(configs, str(ctx.guild.id)), encoding='utf-8')
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'errtitle')), description=eval("f" + get_guild_language(ctx, 'errnorole')), color=0xFF0000)
embed.set_thumbnail(url="https://upload.wikimedia.org/wikipedia/commons/thumb/8/8e/Antu_dialog-error.svg/1024px-Antu_dialog-error.svg.png")
await ctx.respond(embed=embed, delete_after=5)
return False
if role in ctx.author.roles:
return True
else:
config = configparser.ConfigParser()
config.read(os.path.join(configs, str(ctx.guild.id)), encoding='utf-8')
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'errtitle')), description=eval("f" + get_guild_language(ctx, 'errrole')), color=0xFF0000)
embed.set_thumbnail(url="https://upload.wikimedia.org/wikipedia/commons/thumb/8/8e/Antu_dialog-error.svg/1024px-Antu_dialog-error.svg.png")
await ctx.respond(embed=embed, delete_after=5)
return False
def get_bot_uptime():
now = datetime.datetime.utcnow()
delta = now - bot.uptime
hours, remainder = divmod(int(delta.total_seconds()), 3600)
minutes, seconds = divmod(remainder, 60)
days, hours = divmod(hours, 24)
if days:
fmt = '{d} days, {h} hours, {m} minutes, and {s} seconds'
else:
fmt = '{h} hours, {m} minutes, and {s} seconds'
return fmt.format(d=days, h=hours, m=minutes, s=seconds)
def ran():
a = ""
a = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(20))
return a
async def preplay(ctx, source):
voice = ctx.guild.voice_client
if voice:
if voice.is_playing():
if ctx.author.voice:
if voice.channel == ctx.author.voice.channel:
try:
await ctx.author.voice.channel.connect()
except:
pass
addqueue(source, ctx.guild)
return True
else:
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'errtitle')), description=eval("f" + get_guild_language(ctx, 'errvoice')), color=0xFF0000)
await ctx.respond(embed=embed, delete_after=5)
return False
else:
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'errtitle')), description=eval("f" + get_guild_language(ctx, 'erruvc')), color=0xFF0000)
await ctx.respond(embed=embed, delete_after=5)
return False
else:
if ctx.author.voice:
if not voice.channel == ctx.author.voice.channel:
await voice.move_to(ctx.author.voice.channel)
addqueue(source, ctx.guild)
nextqueue(ctx.guild, ctx.author.voice.channel.id)
return True
else:
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'errtitle')), description=eval("f" + get_guild_language(ctx, 'erruvc')), color=0xFF0000)
await ctx.respond(embed=embed, delete_after=5)
return False
else:
if ctx.author.voice:
try:
channid = ctx.author.voice.channel.id
except:
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'errtitle')), description=eval("f" + get_guild_language(ctx, 'erruvc')), color=0xFF0000)
await ctx.respond(embed=embed, delete_after=5)
return False
try:
voice = await ctx.author.voice.channel.connect()
except:
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'errtitle')), description=eval("f" + get_guild_language(ctx, 'errcantconnect')), color=0xFF0000)
await ctx.respond(embed=embed, delete_after=5)
return False
addqueue(source, ctx.guild)
nextqueue(ctx.guild, channid)
return True
else:
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'errtitle')), description=eval("f" + get_guild_language(ctx, 'erruvc')), color=0xFF0000)
await ctx.respond(embed=embed, delete_after=5)
return False
def play(source, guild, channelid):
try:
voice = discord.utils.get(bot.voice_clients, guild=guild)
if voice:
if voice.is_connected():
resettimer(guild)
voice.play(discord.FFmpegPCMAudio(source), after=lambda e: nextqueue(guild, channelid))
else:
resetqueue(guild.id)
else:
resetqueue(guild.id)
except Exception as e:
print(e)
def addqueue(source, guild):
global temp
if os.path.isfile(os.path.join(temp, str(guild.id), "queue")):
with open(os.path.join(temp, str(guild.id), "queue"), "rb") as f:
queue = pickle.load(f)
queue.append(source)
with open(os.path.join(temp, str(guild.id), "queue"), "wb") as f:
pickle.dump(queue, f)
else:
with open(os.path.join(temp, str(guild.id), "queue"), "wb") as f:
queue = []
queue.append(source)
pickle.dump(queue, f)
def nextqueue(guild, channelid):
global temp
if os.path.isfile(os.path.join(temp, str(guild.id), "queue")):
with open(os.path.join(temp, str(guild.id), "queue"), "rb") as f:
queue = pickle.load(f)
if len(queue) >= 1:
source = queue[0]
queue.pop(0)
with open(os.path.join(temp, str(guild.id), "queue"), "wb") as f:
pickle.dump(queue, f)
voice = discord.utils.get(bot.voice_clients, guild=guild)
if voice:
if voice.channel.id == channelid:
play(source, guild, channelid)
else:
resetqueue(guild.id)
else:
os.remove(os.path.join(temp, str(guild.id), "queue"))
def resetqueue(guildid):
global temp
os.remove(os.path.join(temp, str(guildid), "queue"))
async def check_update():
try:
r = requests.get('https://api.github.com/repos/CoccodrillooXDS/TTS-bot/releases/latest', timeout=5)
if r.status_code == 200:
with open(os.path.join(root, 'version.ini'), 'r') as f:
version = f.read()
if int(version) > r.json()['id'] and bot_version != r.json()['tag_name']:
print(f"-> Bot version ({bot_version}) is newer than the latest version ({r.json()['tag_name']})")
return
if bot_version != r.json()['tag_name'] and int(version) == r.json()['id']:
print(f"-> Bot version ({bot_version}) is newer than the latest version ({r.json()['tag_name']})")
return
if r.json()['tag_name'] != bot_version:
print(f"-> New version {r.json()['tag_name']} available!")
if int(version) != r.json()['id'] and bot_version == r.json()['tag_name']:
changelog = r.json()['body']
id = r.json()['id']
with open(os.path.join(root,'version.ini'), 'w') as versionfile:
versionfile.write(str(id))
silent = False
for attachment in r.json()['assets']:
if attachment['name'] == "silent":
silent = True
break
if silent:
print(f"-> A new silent version ({bot_version}) has been installed successfully!")
return
else:
print(f"-> A new version ({bot_version}) has been installed successfully!")
for guild in bot.guilds:
ctx = guild
config = configparser.ConfigParser()
config.read(os.path.join(configs, str(guild.id)), encoding='utf-8')
if config['DEFAULT']['silenceupdates'] == "True":
print(f"!> Update message not sent to {guild.name} ({guild.id}). Updates have been silenced")
continue
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'updatetitle')), description=eval("f" + get_guild_language(ctx, 'updatedesc')), color=0x286fad)
try:
if config['DEFAULT']['updateschannel'] == "system":
await guild.get_channel(guild.system_channel.id).send(embed=embed)
print(f">> Update message sent to {guild.name} ({guild.id}) in system channel {guild.system_channel.name}.")
else:
await guild.get_channel(int(config['DEFAULT']['updateschannel'])).send(embed=embed)
print(f">> Update message sent to {guild.name} ({guild.id}) in {guild.get_channel(int(config['DEFAULT']['updateschannel'])).name}.")
except:
try:
for channel in guild.text_channels:
if channel.permissions_for(guild.me).send_messages:
await channel.send(embed=embed)
print(f">> Update message sent to {guild.name} ({guild.id}) in {channel.name}. << Unable to find the channel specified in the config file.")
break
except:
print(f"!> Update message not sent to {guild.name} ({guild.id}). << Unable to find a channel where I can send messages.")
continue
elif r.status_code == 403:
print("-> Unable to check for bot updates!")
except Exception as e:
print("-> An error occurred while checking for bot updates!")
print(logging.error(traceback.format_exc()))
# --------------------------------------------------
# Languages available
# --------------------------------------------------
@bot.slash_command(name="langs", description="List all available languages")
async def langs(ctx):
global supported_languages_message
""" List all available languages """
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'avlang')), description=supported_languages_message, color=0x37ff00)
await ctx.respond(embed=embed)
# --------------------------------------------------
# Convert text to speech and play it in the voice channel
# --------------------------------------------------
@bot.slash_command(name="say", description="Convert text to speech", default_permissions=False)
@commands.check(check_role)
async def say(ctx, lang: Option(str, "Choose a language", autocomplete=showlangs), text: Option(str, "Enter text to convert to speech")):
global temp
await ctx.defer()
config = configparser.ConfigParser()
author = ctx.author.id
authorname = ctx.author.name
authornick = ctx.author.display_name
lang = lang.lower()
texta = text.lower()
if not lang in lang_list:
config.read(os.path.join(configs, str(ctx.guild.id)), encoding='utf-8')
lang = config['DEFAULT']['defvoice']
if "gg" in texta and "it" in lang:
texta = re.sub(r"\bgg\b", "g g", texta)
texta = "".join(texta)
user = re.findall(r"<@!?(\d+)>", texta)
if user:
for x in user:
try:
u = await bot.fetch_user(int(x))
except:
texta = re.sub(r"<@!?({})>".format(x), "Invalid User", texta)
continue
texta = re.sub(r"<@!?({})>".format(x), u.name, texta)
chann = re.findall(r"<#(\d+)>", texta)
if chann:
for x in chann:
try:
c = await bot.fetch_channel(int(x))
except:
texta = re.sub(r"<#({})>".format(x), "Invalid Channel", texta)
continue
texta = re.sub(r"<#({})>".format(x), c.name, texta)
role = re.findall(r"<@&(\d+)>", texta)
if role:
for x in role:
try:
r = ctx.guild.get_role(int(x))
except:
texta = re.sub(r"<@&({})>".format(x), "Invalid Role", texta)
continue
texta = re.sub(r"<@&({})>".format(x), r.name, texta)
texta = re.sub(r"<\/(\w+):(\d+)>", r"\1", texta)
texta = re.sub(r"<a?:(\w+):(\d+)>", r"\1", texta)
texta = re.sub(r"<:(\w+):(\d+)>", r"\1", texta)
time1 = re.findall(r"<t:(\d+)>", texta)
if time1:
for x in time1:
t = datetime.datetime.fromtimestamp(int(x))
texta = re.sub(r"<t:({})>".format(x), t.strftime("%A %d %B %Y, %H:%M:%S"), texta)
time2 = re.findall(r"<t:(\d+):(\w+)>", texta)
if time2:
for x in time2:
t = datetime.datetime.fromtimestamp(int(x[0]))
texta = re.sub(r"<t:({}):({})>".format(x[0], x[1]), t.strftime("%A %d %B %Y, %H:%M:%S"), texta)
users = []
if os.path.isfile(os.path.join(temp, str(ctx.guild.id), ".users")):
with open(os.path.join(temp, str(ctx.guild.id), ".users"), "rb") as f:
users = pickle.load(f)
if not author in users:
users.append(author)
with open(os.path.join(temp, str(ctx.guild.id), ".users"), "wb") as f:
pickle.dump(users, f)
if len(users) > 1:
config.read(os.path.join(configs, str(ctx.guild.id)), encoding='utf-8')
if config['DEFAULT']['multiuser'] == "True":
if config['DEFAULT']['usenicknames'] == "True":
texta = f"{authornick}: {texta}"
else:
texta = f"{authorname}: {texta}"
else:
users.append(author)
with open(os.path.join(temp, str(ctx.guild.id), ".users"), "wb") as f:
pickle.dump(users, f)
tts = gTTS(texta, lang=lang)
if os.name == 'nt':
source = f"{temp}\{ctx.guild.id}\{ran()}.mp3"
else:
source = f"{temp}/{ctx.guild.id}/{ran()}.mp3"
try:
tts.save(source)
except gTTSError:
code = generate_random_code()
e = traceback.format_exc()
print(e + "Error Code: " + code)
embed = discord.Embed(title=eval("f" + get_guild_language(ctx, 'errtitle')), description=eval("f" + get_guild_language(ctx, 'unexpectederror')), color=0xFF0000)
await ctx.respond(embed=embed, delete_after=5)
return
if await preplay(ctx, source):
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'done')), description=eval("f" + get_guild_language(ctx, 'saylangmess')), color=0x1eff00)
await ctx.respond(embed=embed, allowed_mentions=discord.AllowedMentions(replied_user=False))
async def hidsay(ctx, lang, text):
global temp
await ctx.defer()
config = configparser.ConfigParser()
author = ctx.author.id
authorname = ctx.author.name
authornick = ctx.author.display_name
lang = lang.lower()
texta = text.lower()
if not lang in lang_list:
config.read(os.path.join(configs, str(ctx.guild.id)), encoding='utf-8')
lang = config['DEFAULT']['defvoice']
if "gg" in texta and "it" in lang:
texta = re.sub(r"\bgg\b", "g g", texta)
texta = "".join(texta)
if texta == "" or texta.isspace():
embed = discord.Embed(title=eval("f" + get_guild_language(ctx, 'errtitle')), description=eval("f" + get_guild_language(ctx, 'errnoarg')), color=0xFF0000)
await ctx.respond(embed=embed, delete_after=5)
return
user = re.findall(r"<@!?(\d+)>", texta)
if user:
for x in user:
try:
u = await bot.fetch_user(int(x))
except:
texta = re.sub(r"<@!?({})>".format(x), "Invalid User", texta)
continue
texta = re.sub(r"<@!?({})>".format(x), u.name, texta)
chann = re.findall(r"<#(\d+)>", texta)
if chann:
for x in chann:
try:
c = await bot.fetch_channel(int(x))
except:
texta = re.sub(r"<#({})>".format(x), "Invalid Channel", texta)
continue
texta = re.sub(r"<#({})>".format(x), c.name, texta)
role = re.findall(r"<@&(\d+)>", texta)
if role:
for x in role:
try:
r = ctx.guild.get_role(int(x))
except:
texta = re.sub(r"<@&({})>".format(x), "Invalid Role", texta)
continue
texta = re.sub(r"<@&({})>".format(x), r.name, texta)
texta = re.sub(r"<\/(\w+):(\d+)>", r"\1", texta)
texta = re.sub(r"<a?:(\w+):(\d+)>", r"\1", texta)
texta = re.sub(r"<:(\w+):(\d+)>", r"\1", texta)
time1 = re.findall(r"<t:(\d+)>", texta)
if time1:
for x in time1:
t = datetime.datetime.fromtimestamp(int(x))
texta = re.sub(r"<t:({})>".format(x), t.strftime("%A %d %B %Y, %H:%M:%S"), texta)
time2 = re.findall(r"<t:(\d+):(\w+)>", texta)
if time2:
for x in time2:
t = datetime.datetime.fromtimestamp(int(x[0]))
texta = re.sub(r"<t:({}):({})>".format(x[0], x[1]), t.strftime("%A %d %B %Y, %H:%M:%S"), texta)
users = []
if os.path.isfile(os.path.join(temp, str(ctx.guild.id), ".users")):
with open(os.path.join(temp, str(ctx.guild.id), ".users"), "rb") as f:
users = pickle.load(f)
if not author in users:
users.append(author)
with open(os.path.join(temp, str(ctx.guild.id), ".users"), "wb") as f:
pickle.dump(users, f)
if len(users) > 1:
config.read(os.path.join(configs, str(ctx.guild.id)), encoding='utf-8')
if config['DEFAULT']['multiuser'] == "True":
if config['DEFAULT']['usenicknames'] == "True":
texta = f"{authornick}: {texta}"
else:
texta = f"{authorname}: {texta}"
else:
users.append(author)
with open(os.path.join(temp, str(ctx.guild.id), ".users"), "wb") as f:
pickle.dump(users, f)
tts = gTTS(texta, lang=lang)
if os.name == 'nt':
source = f"{temp}\{ctx.guild.id}\{ran()}.mp3"
else:
source = f"{temp}/{ctx.guild.id}/{ran()}.mp3"
try:
tts.save(source)
except gTTSError:
code = generate_random_code()
e = traceback.format_exc()
print(e + "Error Code: " + code)
embed = discord.Embed(title=eval("f" + get_guild_language(ctx, 'errtitle')), description=eval("f" + get_guild_language(ctx, 'unexpectederror')), color=0xFF0000)
await ctx.respond(embed=embed, delete_after=5)
return
if await preplay(ctx, source):
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'done')), description=eval("f" + get_guild_language(ctx, 'saylangmess')), color=0x1eff00)
await ctx.respond(embed=embed, allowed_mentions=discord.AllowedMentions(replied_user=False), delete_after=1, silent=True)
# --------------------------------------------------
# Disconnect the bot from the voice channel
# --------------------------------------------------
@bot.slash_command(name="stop", description="Disconnect the bot from current channel", default_permissions=False)
@commands.check(check_role)
async def _stop(ctx):
await stop(ctx)
@bot.slash_command(name="disconnect", description="Disconnect the bot from current channel", default_permissions=False)
@commands.check(check_role)
async def disconnect(ctx):
await stop(ctx)
async def stop(ctx):
if ctx.voice_client:
if ctx.voice_client.is_playing():
ctx.voice_client.stop()
await ctx.voice_client.disconnect()
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'done')), description=eval("f" + get_guild_language(ctx, 'disconnected')), color=0x1eff00)
await ctx.respond(embed=embed, delete_after=3)
else:
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'errtitle')), description=eval("f" + get_guild_language(ctx, 'errnovc')), color=0xFF0000)
await ctx.respond(embed=embed, delete_after=3)
# --------------------------------------------------
# Help command
# --------------------------------------------------
class Help(commands.HelpCommand):
async def send_bot_help(self, mapping):
allhelp = f"{eval(get_guild_language(self.context, 'helpprefix'))}\n{eval(get_guild_language(self.context, 'helpsay'))}\n{eval(get_guild_language(self.context, 'helplangs'))}\n{eval(get_guild_language(self.context, 'helpsettings'))}\n{eval(get_guild_language(self.context, 'helpstop'))}\n{eval(get_guild_language(self.context, 'helpabout'))}\n{eval(get_guild_language(self.context, 'helphelp'))}"
embed=discord.Embed(title=eval("f" + get_guild_language(self.context, 'helptitle')), description=allhelp, color=0x1eff00)
await self.context.respond(embed=embed)
async def send_command_help(self, command):
command = eval(get_guild_language(self.context, f'help{command}'))
embed=discord.Embed(title=eval("f" + get_guild_language(self.context, 'helptitle')), description=command, color=0x1eff00)
await self.context.respond(embed=embed)
async def send_group_help(self, group):
allhelp = f"{eval(get_guild_language(self.context, 'helpprefix'))}\n{eval(get_guild_language(self.context, 'helpsay'))}\n{eval(get_guild_language(self.context, 'helplangs'))}\n{eval(get_guild_language(self.context, 'helpsettings'))}\n{eval(get_guild_language(self.context, 'helpstop'))}\n{eval(get_guild_language(self.context, 'helpabout'))}\n{eval(get_guild_language(self.context, 'helphelp'))}"
embed=discord.Embed(title=eval("f" + get_guild_language(self.context, 'helptitle')), description=allhelp, color=0x1eff00)
await self.context.respond(embed=embed)
async def send_cog_help(self, cog):
allhelp = f"{eval(get_guild_language(self.context, 'helpprefix'))}\n{eval(get_guild_language(self.context, 'helpsay'))}\n{eval(get_guild_language(self.context, 'helplangs'))}\n{eval(get_guild_language(self.context, 'helpsettings'))}\n{eval(get_guild_language(self.context, 'helpstop'))}\n{eval(get_guild_language(self.context, 'helpabout'))}\n{eval(get_guild_language(self.context, 'helphelp'))}"
embed=discord.Embed(title=eval("f" + get_guild_language(self.context, 'helptitle')), description=allhelp, color=0x1eff00)
await self.context.respond(embed=embed)
@bot.slash_command(name="help", description="Get help with the bot")
async def help(ctx):
allhelp = f"{eval(get_guild_language(ctx, 'helpprefix'))}\n{eval(get_guild_language(ctx, 'helpsay'))}\n{eval(get_guild_language(ctx, 'helplangs'))}\n{eval(get_guild_language(ctx, 'helpsettings'))}\n{eval(get_guild_language(ctx, 'helpstop'))}\n{eval(get_guild_language(ctx, 'helpabout'))}\n{eval(get_guild_language(ctx, 'helphelp'))}"
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'helptitle')), description=allhelp, color=0x1eff00)
await ctx.respond(embed=embed)
# --------------------------------------------------
# About command
# --------------------------------------------------
@bot.slash_command(name="about", description="About the bot")
async def about(ctx):
global bot_version, punctuation
punct = ' '.join(map(str, punctuation))
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'abouttitle')), description=eval("f" + get_guild_language(ctx, 'aboutdesc')), color=0x1eff00)
await ctx.respond(embed=embed)
# --------------------------------------------------
# Settings command
# --------------------------------------------------
class setrole(Modal):
def __init__(self, ctx, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(InputText(custom_id="role", label=eval("f" + get_guild_language(ctx, 'changerolemodal')), placeholder="TTS", value=""))
async def callback(self, interaction: discord.Interaction):
config = configparser.ConfigParser()
config.read(os.path.join(configs, str(interaction.guild.id)), encoding='utf-8')
newrole = discord.utils.get(interaction.guild.roles, name=self.children[0].value)
oldroleconf = config['DEFAULT']['role']
oldrole = discord.utils.get(interaction.guild.roles, name=oldroleconf)
warnrem = f"{eval('f' + get_guild_language(interaction, 'rolechange'))}\n{eval('f' + get_guild_language(interaction, 'rolenotdeleted'))}"
warnedit = f"{eval('f' + get_guild_language(interaction, 'rolechange'))}\n{eval('f' + get_guild_language(interaction, 'rolenotedited'))}"
code = generate_random_code()
errorembed=discord.Embed(title=eval("f" + get_guild_language(interaction, 'errtitle')), description=eval("f" + get_guild_language(interaction, 'unexpectederrorrole')), color=0xff0000)
warningremoveembed=discord.Embed(title=eval("f" + get_guild_language(interaction, 'done')), description=warnrem, color=0xf0e407)
warningeditembed=discord.Embed(title=eval("f" + get_guild_language(interaction, 'done')), description=warnedit, color=0xf0e407)
embed=discord.Embed(title=eval("f" + get_guild_language(interaction, 'done')), description=eval("f" + get_guild_language(interaction, 'rolechange')), color=0x1eff00)
if oldrole is None and newrole is None:
try:
await interaction.guild.create_role(name=self.children[0].value)
print(f"{interaction.guild.name}: Created role {self.children[0].value}")
except:
e = traceback.format_exc()
print(f"Error: Could not create role {self.children[0].value} in {interaction.guild.name}")
print(e + "Error Code: " + code)
await interaction.response.send_message(embed=errorembed, delete_after=10, ephemeral=True)
return
if oldrole is not None and newrole is None:
try:
await oldrole.edit(name=self.children[0].value)
print(f"{interaction.guild.name}: Old role {oldroleconf} renamed to {self.children[0].value}")
newrole = discord.utils.get(interaction.guild.roles, name=self.children[0].value)
except:
e = traceback.format_exc()
print(f"Error: Could not edit role name from {oldroleconf} to {self.children[0].value} in {interaction.guild.name}\{e}")
embed = warningeditembed
try:
await interaction.guild.create_role(name=self.children[0].value)
print(f"{interaction.guild.name}: Warning: Created new role (unable to edit the old role) {self.children[0].value}")
newrole = discord.utils.get(interaction.guild.roles, name=self.children[0].value)
except:
e = traceback.format_exc()
print(f"Error: Could not edit {oldroleconf} and could not create role {self.children[0].value} in {interaction.guild.name}")
print(e + "Error Code: " + code)
await interaction.response.send_message(embed=errorembed, delete_after=10, ephemeral=True)
return
if newrole:
if newrole.id not in interaction.user.roles:
try:
await interaction.user.add_roles(newrole)
print(f"{interaction.guild.name}: {interaction.user.name} has been given {newrole.name}")
except:
e = traceback.format_exc()
print(f"Error: Could not add the role {newrole.name} to {interaction.user.name}")
print(e + "Error Code: " + code)
await interaction.response.send_message(embed=errorembed, delete_after=10, ephemeral=True)
return
oldrole = discord.utils.get(interaction.guild.roles, name=oldroleconf)
await asyncio.sleep(0.5)
if oldrole is not None and newrole is not None:
try:
await oldrole.delete()
print(f"{interaction.guild.name}: Deleted role {oldrole.name}")
except:
e = traceback.format_exc()
print(f"Error: Could not delete old role from {interaction.guild.name}\n{e}")
embed = warningremoveembed
config['DEFAULT']['role'] = self.children[0].value
with open(os.path.join(configs, str(interaction.guild.id)), 'w') as configfile:
config.write(configfile)
await interaction.response.send_message(embed=embed, delete_after=3, ephemeral=True)
@bot.slash_command(name="settings", description="Edit bot configuration", default_permissions=False)
@commands.check(check_role)
async def settings(ctx):
context = ctx
await ctx.defer()
await _settings(ctx, context)
@bot.slash_command(name="config", description="Edit bot configuration", default_permissions=False)
@commands.check(check_role)
async def config(ctx):
context = ctx
await ctx.defer()
await _settings(ctx, context)
async def _settings(ctx, context):
global lang_list
config = configparser.ConfigParser()
config.read(os.path.join(configs, str(ctx.guild.id)), encoding='utf-8')
aj = json.loads(config["DEFAULT"]["autosaychan"])
asc = ""
for i in aj:
if asc == "":
asc += f"<#{i}>"
else:
asc += f"__, __<#{i}>"
if config["DEFAULT"]["silenceupdates"] == "True":
sus = eval("f" + get_guild_language(ctx, 'enabled'))
else:
if config["DEFAULT"]["silenceupdates"] == "False":
sus = eval("f" + get_guild_language(ctx, 'disabled'))
if config["DEFAULT"]["multiuser"] == "True":
mus = eval("f" + get_guild_language(ctx, 'enabled'))
else:
if config["DEFAULT"]["multiuser"] == "False":
mus = eval("f" + get_guild_language(ctx, 'disabled'))
if config["DEFAULT"]["usenicknames"] == "True":
un = eval("f" + get_guild_language(ctx, 'enabled'))
else:
if config["DEFAULT"]["usenicknames"] == "False":
un = eval("f" + get_guild_language(ctx, 'disabled'))
usci = 0
if config["DEFAULT"]["updateschannel"] == "system" or config["DEFAULT"]["updateschannel"] == "":
try:
uc = f"<#{ctx.guild.system_channel.id}>"
usci = ctx.guild.system_channel.id
except AttributeError:
for channel in ctx.guild.text_channels:
if channel.permissions_for(ctx.guild.me).send_messages:
uc = f"<#{channel.id}>"
usci = channel.id
break
else:
uc = f"<#{config['DEFAULT']['updateschannel']}>"
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'currsettingstitle')), description=eval("f" + get_guild_language(ctx, 'currsettings')), color=0x1eff00)
buttonclose = Button(custom_id="close", label=eval("f" + get_guild_language(ctx, 'close')), style=discord.ButtonStyle.danger)
buttonchangelanguage = Button(custom_id="cl", label=eval("f" + get_guild_language(ctx, 'changelang')), style=discord.ButtonStyle.secondary, emoji="🏴☠️")
buttonchangerole = Button(custom_id="cr", label=eval("f" + get_guild_language(ctx, 'changerole')), style=discord.ButtonStyle.secondary, emoji="🏷️")
buttondefvoice = Button(custom_id="cdv", label=eval("f" + get_guild_language(ctx, 'changedefaultvoice')), style=discord.ButtonStyle.secondary, emoji="🗣️")
buttonautosaychan = Button(custom_id="casc", label=eval("f" + get_guild_language(ctx, 'changeautosaychannel')), style=discord.ButtonStyle.secondary, emoji="#️⃣")
buttonchangeupdatechannel = Button(custom_id="cuc", label=eval("f" + get_guild_language(ctx, 'changeupdatechannel')), style=discord.ButtonStyle.secondary, emoji="🗣️")
buttonsilenceupdates = Button(custom_id="su", label=eval("f" + get_guild_language(ctx, 'silenceupdates')), style=discord.ButtonStyle.secondary, emoji="🔇")
buttonmultiuser = Button(custom_id="mu", label=eval("f" + get_guild_language(ctx, 'multiuser')), style=discord.ButtonStyle.secondary, emoji="👥")
buttonusenicknames = Button(custom_id="un", label=eval("f" + get_guild_language(ctx, 'usenicknames')), style=discord.ButtonStyle.secondary, emoji="🏷️")
view = View()
view.add_item(buttonchangerole)
view.add_item(buttonchangelanguage)
view.add_item(buttondefvoice)
view.add_item(buttonautosaychan)
view.add_item(buttonchangeupdatechannel)
view.add_item(buttonsilenceupdates)
view.add_item(buttonmultiuser)
view.add_item(buttonusenicknames)
view.add_item(buttonclose)
await ctx.respond(embed=embed, view=view, delete_after=20)
async def defvoice(ctx):
config.read(os.path.join(configs, str(ctx.guild.id)), encoding='utf-8')
dv = config['DEFAULT']['defvoice']
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'changedefaultvoice')), description=eval("f" + get_guild_language(ctx, 'changedefaultvoicedesc')), color=0x1eff00)
options1 = []
options2 = []
options3 = []
options4 = []
for i in lang_list:
if len(options1) < 25:
options1.append(discord.SelectOption(label=i, value=i))
elif len(options1) == 25 and len(options2) < 25:
options2.append(discord.SelectOption(label=i, value=i))
elif len(options1) == 25 and len(options2) == 25 and len(options3) < 25:
options3.append(discord.SelectOption(label=i, value=i))
elif len(options1) == 25 and len(options2) == 25 and len(options3) == 25 and len(options4) < 25:
options4.append(discord.SelectOption(label=i, value=i))
view = View()
async def callback(ctx):
try:
if select.values:
config.set('DEFAULT', 'defvoice', select.values[0])
except IndexError:
config.set('DEFAULT', 'defvoice', dv)
except NameError:
pass
try:
if select2.values:
config.set('DEFAULT', 'defvoice', select2.values[0])
except IndexError:
config.set('DEFAULT', 'defvoice', dv)
except NameError:
pass
try:
if select3.values:
config.set('DEFAULT', 'defvoice', select3.values[0])
except IndexError:
config.set('DEFAULT', 'defvoice', dv)
except NameError:
pass
try:
if select4.values:
config.set('DEFAULT', 'defvoice', select4.values[0])
except IndexError:
config.set('DEFAULT', 'defvoice', dv)
except NameError:
pass
with open(os.path.join(configs, str(ctx.guild.id)), 'w') as configfile:
config.write(configfile)
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'done')), color=0x1eff00)
await ctx.message.delete()
await ctx.response.send_message(embed=embed, delete_after=1)
await _settings(context, context)
if len(options1) > 0:
select = Select(custom_id="defvoice", max_values=1, options=options1)
view.add_item(select)
select.callback = callback
if len(options2) > 0:
select2 = Select(custom_id="defvoice2", max_values=1, options=options2)
view.add_item(select2)
select2.callback = callback
if len(options3) > 0:
select3 = Select(custom_id="defvoice3", max_values=1, options=options3)
view.add_item(select3)
select3.callback = callback
if len(options4) > 0:
select4 = Select(custom_id="defvoice4", max_values=1, options=options4)
view.add_item(select4)
select4.callback = callback
await ctx.message.delete()
await ctx.response.send_message(embed=embed, view=view)
buttondefvoice.callback = defvoice
async def autosaychan(ctx):
config.read(os.path.join(configs, str(ctx.guild.id)), encoding='utf-8')
ascj = json.loads(config['DEFAULT']['autosaychan'])
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'changeautosaychannel')), color=0x1eff00)
options = []
options2 = []
options3 = []
optsel = []
optsel2 = []
optsel3 = []
for i in ctx.guild.text_channels:
if len(options) < 25:
if int(i.id) in ascj:
options.append(discord.SelectOption(label=i.name, value=str(i.id), default=True))
optsel.append(i.id)
else:
options.append(discord.SelectOption(label=i.name, value=str(i.id)))
elif len(options) == 25 and len(options2) < 25:
if int(i.id) in ascj:
options2.append(discord.SelectOption(label=i.name, value=str(i.id), default=True))
optsel2.append(i.id)
else:
options2.append(discord.SelectOption(label=i.name, value=str(i.id)))
elif len(options) == 25 and len(options2) == 25 and len(options3) < 25:
if int(i.id) in ascj:
options3.append(discord.SelectOption(label=i.name, value=str(i.id), default=True))
optsel3.append(i.id)
else:
options3.append(discord.SelectOption(label=i.name, value=str(i.id)))
lo1 = len(options)
lo2 = len(options2)
lo3 = len(options3)
async def onlysel(ctx):
try:
await ctx.response.send_message(" ", ephemeral=True, delete_after=0)
except:
pass
view = View()
if lo1 > 25:
lo1 = 25
if not lo1 == 0:
select = Select(custom_id="autosaychan", min_values=0, max_values=lo1, options=options)
view.add_item(select)
select.callback = onlysel
if lo2 > 25:
lo2 = 25
if not lo2 == 0:
select2 = Select(custom_id="autosaychan2", min_values=0, max_values=lo2, options=options2)
view.add_item(select2)
select2.callback = onlysel
if lo3 > 25:
lo3 = 25
if not lo3 == 0:
select3 = Select(custom_id="autosaychan3", min_values=0, max_values=lo3, options=options3)
view.add_item(select3)
select3.callback = onlysel
buttonapply = Button(custom_id="apply", label=eval("f" + get_guild_language(ctx, 'apply')), style=discord.ButtonStyle.primary, emoji="✅")
if optsel == [] and optsel2 == [] and optsel3 == []:
buttondisable = Button(custom_id="disable", disabled=True, label=eval("f" + get_guild_language(ctx, 'disable')), style=discord.ButtonStyle.danger)
else:
buttondisable = Button(custom_id="disable", label=eval("f" + get_guild_language(ctx, 'disable')), style=discord.ButtonStyle.danger)
view.add_item(buttonapply)
view.add_item(buttondisable)
await ctx.message.delete()
await ctx.response.send_message(embed=embed, view=view)
async def callback(ctx):
channels = []
try:
for channel in select.values:
channels.append(int(channel))
if not select.values:
channels.extend(optsel)
except NameError:
pass
try:
for channel in select2.values:
channels.append(int(channel))
if not select2.values:
channels.extend(optsel2)
except NameError:
pass
try:
for channel in select3.values:
channels.append(int(channel))
if not select3.values:
channels.extend(optsel3)
except NameError:
pass
config.set('DEFAULT', 'autosaychan', str(channels))
with open(os.path.join(configs, str(ctx.guild.id)), 'w') as configfile:
config.write(configfile)
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'done')), color=0x1eff00)
await ctx.message.delete()
await ctx.response.send_message(embed=embed, delete_after=1)
await _settings(context, context)
buttonapply.callback = callback
async def disable(ctx):
channels = []
config.set('DEFAULT', 'autosaychan', str(channels))
with open(os.path.join(configs, str(ctx.guild.id)), 'w') as configfile:
config.write(configfile)
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'disabledautosay')), color=0xe32222)
await ctx.message.delete()
await ctx.response.send_message(embed=embed, delete_after=3)
await asyncio.sleep(2)
await _settings(context, context)
buttondisable.callback = disable
await view.wait()
buttonautosaychan.callback = autosaychan
async def close(ctx):
await ctx.message.delete()
buttonclose.callback = close
async def changerole(ctx):
await ctx.message.delete()
modal = setrole(ctx, title=eval("f" + get_guild_language(ctx, 'changerole')))
await ctx.response.send_modal(modal)
await modal.wait()
await _settings(context, context)
buttonchangerole.callback = changerole
async def changelanguage(ctx):
global installed_langs
language = config["DEFAULT"]["lang"]
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'changelang')), description=eval("f" + get_guild_language(ctx, 'changelangdrop')), color=0x1eff00)
options = []
for i in installed_langs:
options.append(discord.SelectOption(label=i, value=i))
select = Select(custom_id="selecta", max_values=1, placeholder=language, options=options)
view = View()
view.add_item(select)
await ctx.message.delete()
await ctx.response.send_message(embed=embed, view=view, ephemeral=True)
async def callback(ctx):
try:
config.set('DEFAULT', 'lang', select.values[0])
except IndexError:
config.set('DEFAULT', 'lang', language)
with open(os.path.join(configs, str(ctx.guild.id)), 'w') as configfile:
config.write(configfile)
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'done')), description=eval("f" + get_guild_language(ctx, 'changedlang')), color=0x1eff00)
await ctx.response.edit_message(embed=embed, view=None)
await _settings(context, context)
select.callback = callback
buttonchangelanguage.callback = changelanguage
async def changeupdatechannel(ctx):
config.read(os.path.join(configs, str(ctx.guild.id)), encoding='utf-8')
chanid = config["DEFAULT"]["updateschannel"]
embed=discord.Embed(title=eval("f" + get_guild_language(ctx, 'changeupdatechannel')), color=0x1eff00)
options1 = []
options2 = []
options3 = []
options4 = []
for i in ctx.guild.text_channels:
if len(options1) < 25:
if str(i.id) == chanid or i.id == usci:
options1.append(discord.SelectOption(label=i.name, value=str(i.id), default=True))
else:
options1.append(discord.SelectOption(label=i.name, value=str(i.id)))
elif len(options1) == 25 and len(options2) < 25:
if str(i.id) == chanid or i.id == usci:
options2.append(discord.SelectOption(label=i.name, value=str(i.id), default=True))
else:
options2.append(discord.SelectOption(label=i.name, value=str(i.id)))
elif len(options1) == 25 and len(options2) == 25 and len(options3) < 25:
if str(i.id) == chanid or i.id == usci:
options3.append(discord.SelectOption(label=i.name, value=str(i.id), default=True))
else:
options3.append(discord.SelectOption(label=i.name, value=str(i.id)))
elif len(options1) == 25 and len(options2) == 25 and len(options3) == 25 and len(options4) < 25:
if str(i.id) == chanid or i.id == usci:
options4.append(discord.SelectOption(label=i.name, value=str(i.id), default=True))
else:
options4.append(discord.SelectOption(label=i.name, value=str(i.id)))