-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.py
563 lines (489 loc) · 23.6 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
from random import choices
import random
from discord.ext import commands
from discord.commands import OptionChoice
from youtube_search import YoutubeSearch
import yt_dlp.utils
import yt_dlp as youtube_dl
import discord
import os
from discord import Option
# ---------------------------------------------- #
# ----------- BOT VARIABLES SECTION ------------ #
# ---------------------------------------------- #
f = open("tokenBot.txt", encoding='utf8')
# You must save your token in a txt file called "tokenBot.txt" and put this file in the directory with your bot.py
TOKEN = f.read().strip()
languageSet = dict()
AvailableLanguage = [
OptionChoice(name="English", value="ENG"),
OptionChoice(name="Italiano", value="ITA"),
]
langDict = dict()
COMMAND_PREFIX = "/"
colore = 0x6897e0
ytlink = "https://www.youtube.com/watch?v="
ydl_opts = {
'format': 'bestaudio',
'geo_bypass': 'True',
'noplaylist': 'True',
'source_address': '0.0.0.0', # ipv6 addresses cause issues sometimes
'force-ipv4': True,
'cachedir': False,
'skip_download': True,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredquality': '192',
}],
}
FFMPEG_OPTS = {
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 10'}
list_queue = dict()
nowPlaying = dict()
searched = dict()
stopped = dict()
global_volume = dict()
youtube_dl.utils.std_headers['Cookie'] = ''
# ---------------------------------------------- #
# ----------- BOT STARTUP SECTION -------------- #
# ---------------------------------------------- #
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=COMMAND_PREFIX,
intents=intents, help_command=None)
def get_String(ctx, string):
return langDict[languageSet[ctx.guild]][string]
def langDictBuilder():
for filename in os.listdir("languages"):
with open(os.path.join("languages", filename), encoding="UTF-8", mode='r') as f:
langDict[filename[:-4]] = dict()
for line in f:
line = line.split(':')
langDict[filename[:-4]][line[0]] = line[1].replace('\n', ' ')
print("Dictionary loaded")
def welcomeBuilder():
with open("files/welcome.txt", encoding="UTF-8", mode='r') as f:
welcome = ""
for line in f:
welcome += line
return welcome
welcome = welcomeBuilder()
# ---------------------------------------------- #
# ----------- SUBMIT SONGS SECTION ------------- #
# ---------------------------------------------- #
@bot.slash_command(name="play", description="Reproduces music from youtube or provided URL")
async def play(ctx: discord.ApplicationContext,
title: Option(str, "Insert an URL or a youtube video name", required=True)):
# We first search for the user that wrote the message
user = ctx.author
guild = ctx.guild
guildStarter(ctx, ctx.guild)
# Than we get our query/url (you can use both!)
if user.voice is None:
# If the user doesn't stay in any voice channel, we send him a message
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "UNF"),
description=get_String(ctx, "UNF2"),
color=colore))
return
# Then we try to connect to his channel
voice_channel = user.voice.channel
# We take the "bot voice" instance
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
# If there is no istance, we connect the bot
if voice is None:
await voice_channel.connect()
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
is_number = False
number = 0
try:
number = int(title)
is_number = True
except ValueError:
is_number = False
if(searched[ctx.guild] is not None and len(searched[ctx.guild]) > 0 and is_number):
message = await ctx.respond(embed=discord.Embed(title=get_String(ctx, "ELB"), color=colore))
try:
await reproduce(ctx, voice, guild, searched[guild][number-1], message)
except IndexError:
await message.edit_original_response(embed=discord.Embed(title=get_String(ctx, "IND"),
description=get_String(ctx, "IND2"),
color=colore))
return
searched[ctx.guild] = list()
return
# Then we search the video on yt
if title.__contains__("list="):
message = await ctx.respond(embed=discord.Embed(title=get_String(ctx, "ELP"), color=colore))
await playlistSetter(ctx, title, message)
else:
message = await ctx.respond(embed=discord.Embed(title=get_String(ctx, "ELB"), color=colore))
await reproduce(ctx, voice, guild, title, message)
@bot.slash_command(name="search", description="Searched music from youtube")
async def search(ctx: discord.ApplicationContext,
title: Option(str, "Insert a youtube video name", required=True),
results: Option(int, "", min_value=1, max_value=10, default=5)):
guildStarter(ctx, ctx.guild)
searched[ctx.guild] = list()
# We first search the title on youtube and the add the results to the searched list
lista = YoutubeSearch(title, max_results=results).to_dict()
# Then we send the results to the user
messageDescription = ""
for i in range(0, results):
messageDescription += "**" + str(i+1) + ")** - " + lista[i]["title"] + "\n"
searched[ctx.guild].append("https://www.youtube.com" + lista[i]['url_suffix'])
message = discord.Embed(title=get_String(ctx, "SRC"),description=get_String(ctx, "MSG") + "\n"
+ messageDescription,color=colore)
await ctx.respond(embed=message)
# ---------------------------------------------- #
# ----------- SONGS ELABORATION SECTION -------- #
# ---------------------------------------------- #
async def reproduce(ctx, voice, guild, titolo, message):
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
try:
info = ydl.extract_info(titolo, download=False)
except youtube_dl.utils.DownloadError:
try:
info = ydl.extract_info(f"ytsearch:{titolo}", download=False)['entries'][0]
except youtube_dl.utils.DownloadError:
await message.edit_original_response(embed=discord.Embed(title=get_String(ctx, "ERB"),
description=get_String(ctx, "ERB2"),
color=colore))
if not voice.is_playing():
await voice.disconnect()
return
except IndexError:
await message.edit_original_response(embed=discord.Embed(title=get_String(ctx, "ERB"),
description=get_String(ctx, "ERB2"),
color=colore))
if not voice.is_playing():
await voice.disconnect()
return
# If something is on right now, we append the new song to the queue
if voice.is_playing() or voice.is_paused():
await message.edit_original_response(embed=discord.Embed(title=get_String(ctx, "QUB"),
description=get_String(ctx, "QUB2") + info['title'] +
get_String(ctx, "QUB3"),
color=colore))
list_queue[guild].append(info)
# If the bot is not playing, we start playing the song
if not(voice.is_playing() or voice.is_paused()):
queue(ctx, message)
def queue(ctx, message=None):
# This is where our queue gets underway
guild = ctx.guild
voice = discord.utils.get(bot.voice_clients, guild=guild)
#We first check if the queue is empty
if len(list_queue[guild]) != 0:
info = list_queue[guild][0]
#If there are elements in the queue, we further check if the first element is a playlist
if list_queue[guild][0]['title'].startswith("**Playlist"):
playlist(ctx)
return
#If the queue is empty, we disconnect the bot
elif len(list_queue[guild]) == 0:
endQueue(ctx)
return
#If not, we finally start to play the song
voice.play(discord.FFmpegPCMAudio(info['url'], **FFMPEG_OPTS),
after=lambda e: queue(ctx))
voice.source = discord.PCMVolumeTransformer(
voice.source, volume=global_volume[guild][0])
nowPlayingSetter(ctx.guild, info)
channel = bot.get_channel(ctx.channel_id)
if message is not None:
bot.loop.create_task(message.edit_original_response(embed=discord.Embed(title=get_String(ctx, "NOW"),
description="**" + info['title'] + "**\n",
color=colore)))
else:
bot.loop.create_task(channel.send(embed=discord.Embed(title=get_String(ctx, "NOW"),
description="**" + info['title'] + "**\n",
color=colore)))
del list_queue[guild][0]
# ---------------------------------------------- #
# ------- PLAYLIST ELABORATION SECTION --------- #
# ---------------------------------------------- #
async def playlistSetter(ctx, titolo, message):
guild = ctx.guild
voice = discord.utils.get(bot.voice_clients, guild=guild)
list_queue[guild].append({'title':"**Playlist** - ", 'index':1, 'url': titolo})
info = playlistFind(ctx, 0, titolo)
if info is None:
return
ptitle = info['title']
list_queue[guild][len(list_queue[guild])-1] = {'title':"**Playlist** - " + ptitle, 'index':1, 'url': titolo}
if voice.is_playing() or voice.is_paused():
await message.edit_original_response(embed=discord.Embed(title=get_String(ctx, "QUP"),
description=get_String(ctx, "QUP2") + ptitle +
get_String(ctx, "QUP3"),
color=colore))
if not(voice.is_playing() or voice.is_paused()):
playlist(ctx, message)
def playlist(ctx, message=None):
guild = ctx.guild
voice = discord.utils.get(bot.voice_clients, guild=guild)
if len(list_queue[guild]) != 0 and not list_queue[guild][0]['title'].startswith("**Playlist"):
queue(ctx)
return
elif len(list_queue[guild]) == 0:
endQueue(ctx)
return
index = list_queue[guild][0]['index']
info = playlistFind(ctx, index, list_queue[guild][0]['url'])
if info is None:
return
try:
ptitle = info['title']
info = info['entries'][0]
except IndexError:
del list_queue[guild][0]
if len(list_queue[guild]) != 0 and list_queue[guild][0]['title'].startswith("**Playlist"):
playlist(ctx)
elif len(list_queue[guild]) == 0:
endQueue(ctx)
else:
queue(ctx)
return
if voice.is_playing() or voice.is_paused():
return
voice.play(discord.FFmpegPCMAudio(info['url'], **FFMPEG_OPTS), after=lambda e: playlist(ctx))
voice.source = discord.PCMVolumeTransformer(voice.source, volume=global_volume[guild][0])
list_queue[ctx.guild][0]['index'] += 1
nowPlayingSetter(ctx.guild, info)
channel = bot.get_channel(ctx.channel_id)
if message is not None:
bot.loop.create_task(message.edit_original_response(embed=discord.Embed(title=get_String(ctx, "NOW"),
description="**" + info['title'] + "**\n" +
get_String(ctx, "PPL") + ptitle + "**\n",
color=colore)))
else:
bot.loop.create_task(channel.send(embed=discord.Embed(title=get_String(ctx, "NOW"),
description="**" + info['title'] + "**\n" +
get_String(ctx, "PPL") + ptitle + "**\n",
color=colore)))
def playlistFind(ctx, index, url):
ydl_opts_p = {
'format': 'bestaudio/best',
'geo_bypass': 'True',
'skip_download': True,
'source_address': '0.0.0.0', # ipv6 addresses cause issues sometimes
'force-ipv4': True,
'cachedir': False,
'playlist_items': str(index),
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}]
}
with youtube_dl.YoutubeDL(ydl_opts_p) as ydln:
try:
info = ydln.extract_info(url, download=False)
except youtube_dl.utils.DownloadError:
bot.loop.create_task(ctx.send(embed=discord.Embed(title=get_String(ctx, "ERB"),
description=get_String(ctx, "ERB2"),
color=colore)))
return None
return info
# ---------------------------------------------- #
# -------------- QUEUE SECTION ----------------- #
# ---------------------------------------------- #
def guildStarter(ctx, guild):
if list_queue.get(guild) is None:
list_queue[guild] = list()
nowPlaying[guild] = list()
searched[guild] = list()
stopped[guild] = False
global_volume[guild] = [0.25]
languageSet[guild] = "ENG"
bot.loop.create_task(ctx.send(embed=discord.Embed(
title="New Guild Setted",
description=welcome,
color=colore)))
def nowPlayingSetter(guild, i):
if len(nowPlaying[guild]) == 0:
nowPlaying[guild].append(ytlink + i['id'])
else:
nowPlaying[guild][0] = ytlink + i['id']
def endQueue(ctx):
if(stopped[ctx.guild] == False):
bot.loop.create_task(ctx.send(embed=discord.Embed(title=get_String(ctx, "BRT"),
description=get_String(ctx, "BRT2"),
color=colore)))
try:
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
bot.loop.create_task(voice.disconnect())
except:
pass
stopped[ctx.guild] = False
@bot.slash_command(name="clear", description="Removes all songs from the queue")
async def clear(ctx: discord.ApplicationContext):
if permessi(ctx):
list_queue[ctx.guild].clear()
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "COD"),
description=get_String(ctx, "COD2"),
color=colore))
@bot.slash_command(name="queue", description="Shows the queue")
async def coda(ctx: discord.ApplicationContext):
contatore = 0
stringa = ""
if permessi(ctx):
if len(list_queue[ctx.guild]) == 0:
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "CDE"),
description=get_String(ctx, "CDE2"),
color=colore))
else:
for elemento in list_queue[ctx.guild]:
contatore += 1
stringa += str(contatore) + "- " + elemento['title'] + "\n"
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "CODA"),
description=stringa,
color=colore))
@bot.slash_command(name="nowplaying", description="Shows the current song")
async def np(ctx: discord.ApplicationContext):
if permessi(ctx):
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
if not voice.is_playing() and not voice.is_paused():
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "SIL"),
description=get_String(ctx, "SIL2"),
color=colore))
else:
await ctx.respond(nowPlaying[ctx.guild][0])
@bot.slash_command(name="remove", description="Removes a song from the queue")
async def remove(ctx: discord.ApplicationContext,
indice: Option(int, "Index of the song (or playlist) to remove", required=True)):
if permessi(ctx):
indice = indice - 1
if indice < len(list_queue[ctx.guild]):
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "REM"),
description=get_String(ctx, "REM2") +
list_queue[ctx.guild][indice]['title'] + "** "
+ get_String(ctx, "REM3"),
color=colore))
del list_queue[ctx.guild][indice]
else:
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "IND"),
description=get_String(ctx, "IND2"),
color=colore))
@bot.slash_command(name="shuffle", description="Shuffles the queue")
async def shuffle(ctx: discord.ApplicationContext):
if permessi(ctx):
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
if voice.is_connected():
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "SHF"),
color=colore))
random.shuffle(list_queue[ctx.guild])
else:
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "ERR"),
description=get_String(ctx, "ERR6"),
color=colore))
# ---------------------------------------------- #
# ----------- REPRODUCTION SECTION ------------- #
# ---------------------------------------------- #
@bot.slash_command(name="volume", description="Sets the volume")
async def volume(ctx: discord.ApplicationContext,
value: Option(int, "", min_value=1, max_value=100, default=50, required=True)):
# Volume manager
if permessi(ctx):
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
new_volume = float(value)
if 0 <= new_volume <= 100:
global_volume[ctx.guild][0] = new_volume / 100
try:
voice.source.volume = new_volume / 100
except AttributeError:
pass
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "VOL"),
description=get_String(ctx, "VOL2") +
str(new_volume),
color=colore))
else:
# Input control
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "ERR"),
description=get_String(ctx, "ERR2"),
color=colore))
@bot.slash_command(name="skip", description="Skips to the next song")
async def skip(ctx: discord.ApplicationContext):
if permessi(ctx):
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
if voice.is_connected() and voice.is_playing():
message = await ctx.respond(embed=discord.Embed(title=get_String(ctx, "SKP"),
color=colore), delete_after=1)
voice.stop()
else:
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "ERR"),
description=get_String(ctx, "ERR3"),
color=colore))
@bot.slash_command(name="pause", description="Pauses the song")
async def pause(ctx: discord.ApplicationContext):
if permessi(ctx):
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.pause()
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "PAU"),
color=colore))
else:
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "ERR"),
description=get_String(ctx, "ERR3"),
color=colore))
@bot.slash_command(name="resume", description="Resumes the reproduction")
async def resume(ctx: discord.ApplicationContext):
if permessi(ctx):
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
if voice.is_paused():
voice.resume()
await ctx.respond(embed=discord.Embed(title="Riproduzione ripresa",
color=colore))
elif not voice.is_playing():
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "ERR"),
description=get_String(ctx, "ERR3"),
color=colore))
else:
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "ERR"),
description=get_String(ctx, "ERR4"),
color=colore))
@bot.slash_command(name="stop", description="Disconnects the bot and clears the reproduction queue")
async def stop(ctx: discord.ApplicationContext):
if permessi(ctx):
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
if voice.is_playing() or voice.is_paused():
list_queue[ctx.guild].clear()
stopped[ctx.guild] = True
await voice.disconnect()
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "STP"),
color=colore))
else:
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "ERR"),
description=get_String(ctx, "ERR3"),
color=colore))
@bot.slash_command(name="language", description="Set the bot language")
async def language(ctx: discord.ApplicationContext,
newlanguage: Option(str, "Inserisci un link o un titolo di un video di youtube", choices=AvailableLanguage, required=True)):
guildStarter(ctx, ctx.guild)
languageSet[ctx.guild] = newlanguage
await ctx.respond(embed=discord.Embed(title=get_String(ctx, "LAN"),
description=get_String(ctx, "LAN2"),
color=colore))
# ---------------------------------------------- #
def permessi(ctx):
# You surely have seen this function very often, infact this is where we control that the user that
# wrote the message is in a voice channel and if the bot has been called with the /play function
user = ctx.author
if user.voice is None:
bot.loop.create_task(ctx.respond(embed=discord.Embed(title=get_String(ctx, "ERR"),
description=get_String(ctx, "ERR5"),
color=colore)))
return False
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
if voice is None:
bot.loop.create_task(ctx.respond(embed=discord.Embed(title=get_String(ctx, "ERR"),
description=get_String(ctx, "ERR6"),
color=colore)))
return False
# If all is good, just return True
return True
@bot.event
async def on_ready():
langDictBuilder()
welcomeBuilder()
print('Bot server started as nickname {0.user}'.format(bot))
bot.run(TOKEN)