-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
360 lines (315 loc) · 12.7 KB
/
main.py
File metadata and controls
360 lines (315 loc) · 12.7 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
#MARK:Initialization
import os
import discord
import yt_dlp as youtube_dl
import time
import datetime
import asyncio
import threading
import random
from googleapiclient.discovery import build
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('BOT_TOKEN')
PREFIX = os.getenv('PREFIX')
KEY = os.getenv('GOOGLE_KEY')
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
VERSION = os.getenv('VERSION')
FIUMBO = os.getenv('FIUMBO')
intents = discord.Intents.all()
client = discord.Client(intents=intents)
#MARK: On Client Events
@client.event
async def on_ready():
print('____| _) | | \n' + ' | | | | __ `__ \\ __ \\ _ \\ __| \n' + ' __| | | | | | | | | ( | | \n' + ' _| _| \\__,_| _| _| _| _.__/ \\___/ \\__| \n')
print(f'v{VERSION} vivita y coleando!')
print(f'Prefix: {PREFIX}')
await client.change_presence(activity=discord.Game(name=f'-> {PREFIX}?'))
@client.event
async def on_message(message):
if(message.content[:1] != os.getenv('PREFIX') or message.author.id == client.application_id):
return
isAdmin = message.author.id == FIUMBO
message_content = message.content.split(' ')
command = ''
args = ''
if (len(message_content[0]) > 1):
command = message_content[0][1:]
args = message.content[len(command) + 2:] if len(message_content) > 1 else ''
else:
command = message_content[1]
args = message_content[len(command) + 2:] if len(message_content) > 2 else ''
print('Command: '+ command)
print('Arguments: ' + args)
match(command):
case '?' | 'help':
return await show_help(message)
case 'p' | 'play':
return await add_song(message, args)
case 'q' | 'queue':
return await view_queue(message)
case 's' | 'skip':
return await skip_song(message)
case 'r' | 'remove':
return await remove_song(message, args[0])
case 'm' | 'move':
args = args.split(' ')
if (args[0] == ''):
return await message.channel.send('> Me tenes que decir que canción mover, imbécil')
if (len(args) >= 2):
return await move_song(message, args[0], args[1])
elif (len(args) == 1):
return await move_song(message, args[0])
case 'h' | 'hold':
return await play_pause(message)
case '⚽' | 'fifa':
return await fifa(message)
#MARK: Fifa
canciones_fifa = [
'Automotivo Bibi Fogosa',
'Don Omar - Virtual Diva',
'El Retutu - Hoy Volvi a Verte',
'DJ Peligro - Candy Perreo',
'Yerba Brava - La Cumbia de los Trapos',
'Los Wachiturros - Shampein Shower',
'Los Nota Lokos - Sexy Soltera',
'Wisin & Raquel - Rakata',
'El Descanso Cumbiero - Gorda Trola',
'WANDA NARA - O Bicho Vai Pegar 🇧🇷 (Video Oficial)',
'Tiagz - Tacata (Lyrics) i dont speak portuguese i can speak ingles'
]
async def fifa(message):
random.shuffle(canciones_fifa)
for cancion in canciones_fifa:
await add_song(message, cancion)
def get_service():
return build("youtube", "v3", developerKey=KEY)
#MARK: Youtube Search
def search_yt(query):
service = get_service()
video_id = ''
if ('www.youtube.com' in query):
video_id = query.split('https://www.youtube.com/watch?v=')[1]
elif ('youtu.be' in query):
video_id = query.split('https://youtu.be/')[1].split('?')[0]
else:
video_id = service.search().list(
part="id",
q=query,
safeSearch="none"
).execute()["items"][0]["id"]["videoId"]
video = service.videos().list(
part="contentDetails,snippet",
id=video_id
).execute()
duration = video["items"][0]["contentDetails"]["duration"]
duration = duration[2:].split('H')
rawDuration = 0
prettyDuration = ''
if (len(duration) > 1):
if (int(duration[0]) < 10):
duration[0] = '0' + duration[0]
prettyDuration = duration[0] + ':'
rawDuration += int(duration[0]) * 3600
duration.pop(0)
duration = duration[0].split('M')
if (len(duration) > 1):
if (int(duration[0]) < 10):
duration[0] = '0' + duration[0]
prettyDuration += duration[0] + ':'
rawDuration += int(duration[0]) * 60
duration.pop(0)
else:
prettyDuration += '00:'
duration = duration[0].split('S')
if (len(duration) > 1):
if (int(duration[0]) < 10):
duration[0] = '0' + duration[0]
prettyDuration += duration[0]
rawDuration += int(duration[0])
duration.pop(0)
return Song(video_id, video["items"][0]["snippet"]["title"], prettyDuration,
rawDuration)
#MARK: Help
async def show_help(message):
embed = discord.Embed(color=discord.Colour.green())
embed.title = 'Lista de comandos'
embed.description = '<a> = Parametro obligatorio\n{a} = Parametro opcional'
embed.add_field(name='k? / help', value='Muestra esta lista de comandos', inline=False)
embed.add_field(name='kp <Link de youtube, o busqueda> / play', value='Reproduce un video de youtube', inline=False)
embed.add_field(name='kq / queue', value='Muestra la cola de audios que se van a reproducir', inline=False)
embed.add_field(name='ks / skip', value='Salta el audio que se este reproduciendo', inline=False)
embed.add_field(name='kr <Indice> / remove', value='Elimina un audio de la cola', inline=False)
embed.add_field(name='km <Indice> {Objetivo} / move', value='Mueve un audio a la posición 1 o el objetivo', inline=False)
embed.add_field(name='kh / hold', value='Pausa o resume la reproducción de audio', inline=False)
await message.channel.send(embed=embed)
#MARK: Queue
global queue
queue = []
global voice_connection
voice_connection = None
global task
def view_queue(message):
global queue
if (len(queue) == 0):
return message.reply('> La queue esta vacia')
embed = discord.Embed(color=discord.Colour.blue())
i = 0
for item in queue:
if (i < 25):
if (i == 0):
embed.add_field(name=f'▶️ {item.title}', value=item.duration, inline=False)
else:
embed.add_field(name=f'{i}. {item.title}', value=item.duration, inline=False)
i += 1
return message.channel.send(embed=embed)
#MARK: Add song to queue
async def add_song(message, args):
if (message.author.voice.channel == None):
return await message.reply('> Tenes que estar en un voice chat')
else:
global queue
if (len(queue) == 25):
return message.channel.send('> ⛔ La queue esta llena ⛔')
global voice_connection
voice_clients = client.voice_clients
if (len(voice_clients) > 0):
voice_connection = voice_clients[0]
else:
vc = message.author.voice.channel
voice_connection = await vc.connect()
songData = search_yt(args)
print(f'Adding {songData.title} to queue')
queue.append(songData)
print(queue)
if (len(queue) == 1 and voice_connection.is_playing() == False):
await play_song(message)
else:
await message.channel.send(f'> Agregando: `{songData.title}` a la queue')
#MARK: Play next song in queue
def play_next(message):
global queue
if (len(queue) > 0):
del queue[0]
if (len(queue) > 0):
global voice_connection
file = asyncio.run_coroutine_threadsafe(YTDLSource.from_url('https://www.youtube.com/watch?v=' + queue[0].id, loop=client.loop, stream=True),
loop=client.loop).result()
voice_connection.play(file, after=lambda e: play_next(message))
#MARK: Play song if queue is empty
async def play_song(message):
global queue
if (len(queue) == 0):
return
asyncio.run_coroutine_threadsafe(message.reply(f'> Reproduciendo: `{queue[0].title}`'), loop=client.loop)
file = await YTDLSource.from_url(queue[0].id, loop=client.loop, stream=True)
voice_connection.play(file, after=lambda e: play_next(message))
#MARK: Skip song
async def skip_song(message):
if (message.author.voice.channel == None):
return await message.reply('> Tenes que estar en un voice chat')
if (len(queue) > 0):
global voice_connection
await message.reply(f'> Saltando la canción: `{queue[0].title}`')
del queue[0]
voice_connection.stop()
if (len(queue) > 0):
await play_song(message)
else:
await message.reply('> La queue esta vacia')
#MARK: Remove song from queue
async def remove_song(message, index):
if (message.author.voice.channel == None):
return await message.reply('> Tenes que estar en un voice chat')
global queue
if (len(queue) < 1):
return await message.reply('> La queue esta vacia')
index = int(index)
if (index < 1):
return await message.reply('> El indice tiene que ser mayor a 0')
if (index > 25):
return await message.reply('> El indice tiene que ser menor a 25')
if (len(queue) < index):
return await message.reply('> Ese indice no existe en la queue')
await message.reply(f'> Eliminando el audio {queue[index].title} de la queue')
queue.pop(index)
#MARK: Move songs in queue
async def move_song(message, start, target=None):
if (message.author.voice.channel == None):
return await message.reply('> Tenes que estar en un voice chat')
global queue
if (len(queue) < 1):
return await message.reply('> La queue esta vacia')
start = int(start)
if (start < 1):
return await message.reply('> El indice tiene que ser mayor a 0')
if (start > 25):
return await message.reply('> El indice tiene que ser menor a 25')
if (len(queue) < start):
return await message.reply('> Ese indice no existe en la queue')
song = queue[start]
queue.pop(start)
if (target != None):
target = int(target)
if (target < 1):
return await message.reply('> El indice tiene que ser mayor a 0')
if (target > 25):
return await message.reply('> El indice tiene que ser menor a 25')
if (len(queue) < target):
return await message.reply('> Ese indice no existe en la queue')
queue.insert(target, song)
return await message.reply(f'> Moviendo la canción {song.title} a la posición {target}')
else:
queue.insert(1, song)
return await message.reply(f'> Moviendo la canción {song.title} al primer lugar')
#MARK: Play/Pause
async def play_pause(message):
if (message.author.voice.channel == None):
return await message.reply('> Tenes que estar en un voice chat')
global voice_connection
if (voice_connection != None):
if (voice_connection.is_playing()):
voice_connection.pause()
return await message.channel.send('> ⏸️ Pausando el temon ⏸️')
else:
voice_connection.resume()
return await message.channel.send('> ▶️ Resumiendo la bailanta ▶️')
youtube_dl.utils.bug_reports_message = lambda: ''
ytdl_format_options = {
'format': 'bestaudio/best',
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses cause issues sometimes
}
#MARK: YTDL Initialization
ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, volume=0.5):
super().__init__(source, volume)
self.data = data
self.title = data.get('title')
self.url = ""
@classmethod
async def from_url(cls, url, *, loop=None, stream=False):
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
if 'entries' in data:
# take first item from a playlist
data = data['entries'][0]
filename = data['url'] if stream else ytdl.prepare_filename(data)
return cls(discord.FFmpegPCMAudio(filename, **FFMPEG_OPTIONS), data=data)
#MARK: Song class
class Song:
def __init__(self, id, title, duration, rawDuration):
self.id = id
self.title = title
self.duration = duration
self.rawDuration = rawDuration
client.run(TOKEN)