· 5 years ago · Aug 27, 2020, 05:44 PM
1import asyncio
2import functools
3import itertools
4import math
5import random
6import discord
7from discord.ext import commands
8import asyncio
9import random
10import aiohttp
11import itertools
12from async_timeout import timeout
13#import r6sapi as api
14#from requests.adapters import HTTPAdapter
15#from bs4 import BeautifulSoup
16#import html5lib
17from functools import partial
18from aiohttp import AsyncResolver
19import time
20import re
21#import requests
22from discord.utils import get
23import youtube_dl
24import os
25#import dload
26#import lavalink
27#from googlesearch import search
28from datetime import datetime as dt, date, timedelta
29from discord import utils
30from discord import Embed
31import shutil
32import datetime
33#from PIL import Image
34#from PIL import ImageFont
35#from PIL import ImageDraw
36import json
37import configparser
38from discord.ext import commands
39from discord.utils import get
40from discord import FFmpegPCMAudio
41from os import system
42#from termcolor import colored, cprint
43#from pytz import timezone
44#import urbandictionary
45import webbrowser
46#import praw
47#import urllib3
48import urllib
49import traceback
50import urllib.parse, urllib.request, re
51import sys
52from discord.ext.commands.context import Context
53import logging
54from youtube_dl import YoutubeDL
55#import lxml
56from asyncio.tasks import wait
57import ctypes
58from urllib.parse import urlparse
59import urllib.request
60#import spotipy
61#from spotipy import *
62#from spotipy.oauth2 import SpotifyClientCredentials
63#import spotipy.util as util
64
65try:
66
67 canali_musica = [693003574468411412, 720342575885582456]
68
69
70 a = str("?️")
71 x = str("❌")
72
73
74
75
76 class Gsearch_python:
77 def __init__(self, name_search):
78 self.name = name_search
79 def Gsearch(self):
80 count = 0
81 for i in search(query=self.name,tld='co.in',lang='it',num=10,stop=1,pause=2):
82 count += 1
83 return (i)
84
85 def paginate(lines, chars=2000):
86 size = 0
87 message = []
88 for line in lines:
89 if len(line) + size > chars:
90 yield message
91 message = []
92 size = 0
93 message.append(line)
94 size += len(line)
95 yield message
96
97
98
99 async def lyricsdef(ctx, musica=None):
100 try:
101 vc = ctx.voice_client
102 if not musica:
103 musica = vc.source.title
104 gs = Gsearch_python((f"{musica} lyrics genius"))
105 await ctx.send(embed=discord.Embed(description=f"**Cerco la lyrics per {musica}**", color=discord.Color.orange()))
106 url = gs.Gsearch()
107 soup = BeautifulSoup(requests.get(url).content, 'html.parser')
108 try:
109
110 lyrics = soup.select_one('div[class^="Lyrics__Container"], .lyrics').get_text(strip=True, separator='\n')
111 except Exception as c:
112 print(c)
113 lyrics = soup.select_one('div[class^="lyrics"]').get_text(strip=True, separator='\n')
114
115 # lyrics = lyrics.replace('<br/>', ' ')
116 lyrics = re.sub(r'(\<.*?\>)', '', lyrics)
117 lyrics = re.sub('(\[.*?\])*', '', lyrics)
118 # embed = discord.Embed(title=musica, description=lyrics.strip("\n"), color=discord.Color.orange())
119 # await ctx.send(embed=embed)
120 for message in paginate(lyrics):
121 embed = discord.Embed(color=discord.Color.orange())
122 embed.description = ''.join(message)
123 await ctx.send(embed=embed)
124 except Exception as e:
125 raise(e)
126
127 async def chiedilyrics(ctx, canzone):
128
129 author = ctx.author
130 channel = ctx.channel
131
132 embednps = discord.Embed(title="Yo nigga", color=discord.Color.orange())
133 embednps.add_field(name="Vuoi la lyrics?", value=f"Reagisci con {a}", inline=True)
134 embednps.add_field(name="Non vuoi la lyrics?", value=f"Reagisci con {x} o non fare nulla\nTimeout: 5sec")
135
136 messaggio = await ctx.send(embed=embednps)
137
138 await messaggio.add_reaction(a)
139 await messaggio.add_reaction(x)
140 try:
141 reaction, user = await ctx.bot.wait_for('reaction_add', check=predicate10(messaggio, author, channel), timeout=5)
142 except asyncio.TimeoutError:
143 await messaggio.clear_reactions()
144 await messaggio.delete()
145
146 await ctx.send(embed=discord.Embed(title="K", description="No lyrics 4 u", color=discord.Color.red()), delete_after=3)
147 else:
148 if reaction.emoji == a:
149 await messaggio.delete()
150 embed = discord.Embed(title="OK", description="Ecco la lyrics!", color=discord.Color.orange())
151 await ctx.send(embed=embed, delete_after=2)
152 try:
153 async with timeout(15):
154 await lyricsdef(ctx, canzone)
155 except: pass
156 if reaction.emoji == x:
157 await messaggio.delete()
158
159 await ctx.send(embed=discord.Embed(title="K", description="No lyrics 4 u", color=discord.Color.red()))
160 else:
161 print("cosa cazzo è successo")
162
163 def predicate10(message, author, channel):
164
165 def check(reaction, user):
166 if reaction.message.id != message.id or user == client.user:
167 return False
168 if user == author and reaction.message.channel == channel:
169 return True
170 return check
171
172
173 client = commands.Bot(command_prefix = "*", case_insensitive=True)
174
175 # Silence useless bug reports messages
176 youtube_dl.utils.bug_reports_message = lambda: ''
177
178 class VoiceError(Exception):
179 pass
180
181
182 class YTDLError(Exception):
183 pass
184
185
186 class YTDLSource(discord.PCMVolumeTransformer):
187 YTDL_OPTIONS = {
188 'format': 'bestaudio/best',
189 'extractaudio': True,
190 'audioformat': 'mp3',
191 'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
192 'restrictfilenames': True,
193 'noplaylist': True,
194 'nocheckcertificate': True,
195 'ignoreerrors': False,
196 'logtostderr': False,
197 'quiet': True,
198 'no_warnings': True,
199 'default_search': 'auto',
200 'source_address': '0.0.0.0',
201 }
202
203 FFMPEG_OPTIONS = {
204 'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
205 'options': '-vn',
206 }
207
208 ytdl = youtube_dl.YoutubeDL(YTDL_OPTIONS)
209
210 def __init__(self, ctx: commands.Context, source: discord.FFmpegPCMAudio, *, data: dict, volume: float = 0.5):
211 super().__init__(source, volume)
212
213 self.requester = ctx.author
214 self.channel = ctx.channel
215 self.data = data
216
217 self.uploader = data.get('uploader')
218 self.uploader_url = data.get('uploader_url')
219 date = data.get('upload_date')
220 self.upload_date = date[6:8] + '/' + date[4:6] + '/' + date[0:4]
221 self.title = data.get('title')
222 self.thumbnail = data.get('thumbnail')
223 self.description = data.get('description')
224 self.duration = data.get('duration')
225 self.tags = data.get('tags')
226 self.url = data.get('webpage_url')
227 self.views = data.get('view_count')
228 self.likes = data.get('like_count')
229 self.dislikes = data.get('dislike_count')
230 self.stream_url = data.get('url')
231
232 def __str__(self):
233 return '**{0.title}**, di: **{0.uploader}**'.format(self)
234
235
236 @classmethod
237 async def create_source(cls, ctx: commands.Context, search: str, *, loop: asyncio.BaseEventLoop = None):
238 loop = loop or asyncio.get_event_loop()
239
240 partial = functools.partial(cls.ytdl.extract_info, search, download=False, process=False)
241 data = await loop.run_in_executor(None, partial)
242
243 if data is None:
244 raise YTDLError('Couldn\'t find anything that matches `{}`'.format(search))
245
246 if 'entries' not in data:
247 process_info = data
248 else:
249 process_info = None
250 for entry in data['entries']:
251 if entry:
252 process_info = entry
253 break
254
255 if process_info is None:
256 raise YTDLError('Couldn\'t find anything that matches `{}`'.format(search))
257
258 webpage_url = process_info['webpage_url']
259 partial = functools.partial(cls.ytdl.extract_info, webpage_url, download=False)
260 processed_info = await loop.run_in_executor(None, partial)
261
262 if processed_info is None:
263 raise YTDLError('Couldn\'t fetch `{}`'.format(webpage_url))
264
265 if 'entries' not in processed_info:
266 info = processed_info
267 else:
268 info = None
269 while info is None:
270 try:
271 info = processed_info['entries'].pop(0)
272 except IndexError:
273 raise YTDLError('Couldn\'t retrieve any matches for `{}`'.format(webpage_url))
274
275 return cls(ctx, discord.FFmpegPCMAudio(info['url'], **cls.FFMPEG_OPTIONS), data=info)
276
277 @classmethod
278 async def search_source(cls, ctx: commands.Context, search: str, *, loop: asyncio.BaseEventLoop = None):
279 channel = ctx.channel
280 author = ctx.author
281 loop = loop or asyncio.get_event_loop()
282
283 cls.search_query = '%s%s:%s' % ('ytsearch', 10, ''.join(search))
284
285 partial = functools.partial(cls.ytdl.extract_info, cls.search_query, download=False, process=False)
286 info = await loop.run_in_executor(None, partial)
287
288 cls.search = {}
289 cls.search["title"] = f'Ecco i risultati per:\n**{search}**'
290 cls.search["type"] = 'rich'
291 cls.search["color"] = 0xe67e22
292
293 lst = []
294
295 for e in info['entries']:
296 #lst.append(f'`{info["entries"].index(e) + 1}.` {e.get("title")} **[{YTDLSource.parse_duration(int(e.get("duration")))}]**\n')
297 VId = e.get('id')
298 VUrl = 'https://www.youtube.com/watch?v=%s' % (VId)
299 lst.append(f'{info["entries"].index(e) + 1}) {e.get("title")} **[URL]({VUrl})**\n')
300
301 lst.append('\n**Scrivi un numero per fare una scelta, scrivi `interrompi` per interrompere**')
302 cls.search["description"] = "\n".join(lst)
303
304 em = discord.Embed.from_dict(cls.search)
305 ls = await ctx.send(embed=em, delete_after=45.0)
306
307 def check(msg):
308 return msg.channel == channel and msg.author == author
309
310 try:
311 m = await ctx.bot.wait_for('message', check=check, timeout=45.0)
312
313 except asyncio.TimeoutError:
314 rtrn = 'timeout'
315
316 else:
317 if m.content.isdigit() == True:
318 sel = int(m.content)
319 if 0 < sel <= 10:
320 for key, value in info.items():
321 if key == 'entries':
322 """data = value[sel - 1]"""
323 VId = value[sel - 1]['id']
324 VUrl = 'https://www.youtube.com/watch?v=%s' % (VId)
325 partial = functools.partial(cls.ytdl.extract_info, VUrl, download=False)
326 data = await loop.run_in_executor(None, partial)
327 rtrn = cls(ctx, discord.FFmpegPCMAudio(data['url'], **cls.FFMPEG_OPTIONS), data=data)
328 await ls.delete()
329 else:
330 rtrn = 'sel_invalid'
331 await ls.delete()
332 elif m.content == 'interrompi':
333 rtrn = 'cancel'
334 await ls.delete()
335 else:
336 rtrn = 'sel_invalid'
337 await ls.delete()
338 return rtrn
339
340 @staticmethod
341 def parse_duration(duration: int):
342 minutes, seconds = divmod(duration, 60)
343 hours, minutes = divmod(minutes, 60)
344 days, hours = divmod(hours, 24)
345
346 duration = []
347 if days > 0:
348 duration.append('{} days'.format(days))
349 if hours > 0:
350 duration.append('{} hours'.format(hours))
351 if minutes > 0:
352 duration.append('{} minutes'.format(minutes))
353 if seconds > 0:
354 duration.append('{} seconds'.format(seconds))
355
356 return ', '.join(duration)
357
358
359 class Song:
360 __slots__ = ('source', 'requester')
361
362 def __init__(self, source: YTDLSource):
363 self.source = source
364 self.requester = source.requester
365
366
367 def create_embed(self):
368 embednps = discord.Embed(title="Sto suonando:", color=discord.Color.orange())
369 embednps.add_field(name="Nome:", value=f"{self.source.title}", inline=False)
370 embednps.add_field(name="Richiesta da:", value=f"**<@{self.source.requester.id}>**", inline=True)
371 embednps.add_field(name="Link:", value=f"**[URL]({self.source.url})**", inline=True)
372 embednps.add_field(name="Durata:", value=f"**{datetime.timedelta(seconds=self.source.duration)}**", inline=True)
373 embednps.add_field(name="Caricato da:", value=f"[{self.source.uploader}]({self.source.uploader_url})", inline=True)
374 embednps.add_field(name="Caricato il:", value=f"{self.source.upload_date}", inline=True)
375 embednps.add_field(name="\u200b", value="\u200b", inline=True)
376 embednps.set_thumbnail(url=self.source.thumbnail)
377 return embednps
378
379 def byebyeembed(self):
380 baibai = discord.Embed(title="Yo nigga", description="Sono uscito dal canale, per inattività, ciao ciao", color=discord.Color.orange())
381 return baibai
382
383 class SongQueue(asyncio.Queue):
384 def __getitem__(self, item):
385 if isinstance(item, slice):
386 return list(itertools.islice(self._queue, item.start, item.stop, item.step))
387 else:
388 return self._queue[item]
389
390 def __iter__(self):
391 return self._queue.__iter__()
392
393 def __len__(self):
394 return self.qsize()
395
396 def clear(self):
397 self._queue.clear()
398
399 def shuffle(self):
400 random.shuffle(self._queue)
401
402 def remove(self, index: int):
403 del self._queue[index]
404
405
406 class VoiceState:
407 def __init__(self, bot: commands.Bot, ctx: commands.Context):
408 self.bot = bot
409 self._ctx = ctx
410
411 self.current = None
412 self.voice = None
413 self.next = asyncio.Event()
414 self.songs = SongQueue()
415 self.exists = True
416
417 self._loop = False
418 self._volume = 0.5
419 self.skip_votes = set()
420
421 self.np = None
422
423 self.audio_player = client.loop.create_task(self.audio_player_task())
424
425 def __del__(self):
426 self.audio_player.cancel()
427
428 @property
429 def loop(self):
430 return self._loop
431
432 @loop.setter
433 def loop(self, value: bool):
434 self._loop = value
435
436 @property
437 def volume(self):
438 return self._volume
439
440 @volume.setter
441 def volume(self, value: float):
442 self._volume = value
443
444 @property
445 def is_playing(self):
446 return self.voice and self.current
447
448 async def audio_player_task(self):
449 while True:
450 self.next.clear()
451
452 if not self.loop:
453 # Try to get the next song within 3 minutes.
454 # If no song will be added to the queue in time,
455 # the player will disconnect due to performance
456 # reasons.
457 try:
458 async with timeout(180): # 3 minutes
459 self.current = await self.songs.get()
460 except asyncio.TimeoutError:
461 self.exists = False
462 await self._ctx.send(embed=self.current.byebyeembed(), delete_after=10)
463 self.bot.loop.create_task(self.stop())
464 return
465
466 self.current.source.volume = self._volume
467 self.voice.play(self.current.source, after=self.play_next_song())
468 now = await self.current.source.channel.send(embed=self.current.create_embed())
469 self.np = now
470 await chiedilyrics(self._ctx, self.current.source.title) #lyrics embed
471
472
473 elif self.loop == True:
474 self.now = discord.FFmpegPCMAudio(self.current.source.stream_url, **YTDLSource.FFMPEG_OPTIONS)
475 self.voice.play(self.now, after=self.play_next_song)
476 now = await self.current.source.channel.send(embed=self.current.create_embed())
477 self.np = now
478 await chiedilyrics(self._ctx, self.current.source.title)
479
480 await self.next.wait()
481 try:
482 # We are no longer playing this song...
483 await self.np.delete() #delet song embed
484 except Exception as e:
485 raise(e)
486
487 def play_next_song(self, error=None):
488 if error:
489 raise VoiceError(str(error))
490 print("settato la canzone dopo")
491 self.next.set()
492
493 def skip(self, error=None):
494 if error:
495 raise VoiceError(str(error))
496
497 if self.is_playing:
498 self.voice.stop()
499
500 async def stop(self):
501 self.songs.clear()
502
503 if self.voice:
504 await self.voice.disconnect()
505 self.voice = None
506
507
508 class Music(commands.Cog):
509 def __init__(self, bot: commands.Bot):
510 self.bot = bot
511 self.voice_states = {}
512 self.np = None
513
514 def get_voice_state(self, ctx: commands.Context):
515 state = self.voice_states.get(ctx.guild.id)
516 if not state or not state.exists:
517 state = VoiceState(self.bot, ctx)
518 self.voice_states[ctx.guild.id] = state
519
520 return state
521
522
523
524 async def cog_before_invoke(self, ctx: commands.Context):
525 ctx.voice_state = self.get_voice_state(ctx)
526
527 @commands.command(name='join', aliases=["j"], invoke_without_subcommand=True)
528 async def _join(self, ctx: commands.Context, *, channel: discord.VoiceChannel=None):
529
530 if ctx.guild.id == 539884642367438888:
531 if not ctx.message.channel.id in canali_musica:
532 embed = discord.Embed(title="Nope", description="Per favore, usa i comandi musicali nell'apposito canale <#693003574468411412>", color=discord.Color.orange())
533 return await ctx.send(embed=embed)
534 else:
535 pass
536
537
538 if not channel:
539 try:
540 channel1 = ctx.author.voice.channel
541 except AttributeError:
542 embed = discord.Embed(title="Ma o ", description="Non sei connesso ad un canale coglione", color=discord.Color.red())
543 await ctx.send(embed=embed)
544 vc = ctx.voice_client
545 channel1 = ctx.author.voice.channel
546 if vc:
547 if vc.channel.id == ctx.author.voice.channel.id:
548 embed = discord.Embed(title="AOOOOO", description="Fratellì sono già nel tuo canale, mo ti punto il ferro", color=discord.Color.red())
549 await ctx.send(embed=embed)
550 if vc.channel != channel1:
551 if vc.is_playing() or vc.is_paused():
552 embed = discord.Embed(title="Nope", description="Il bot è già utilizzato da qualcun'altro", color=discord.Color.red())
553 await ctx.send(embed=embed)
554 else:
555 destination = ctx.author.voice.channel
556 if ctx.voice_state.voice:
557 await ctx.voice_state.voice.move_to(destination)
558
559 embed = discord.Embed(title="Fatto!", description=(f"Mi sono connesso al canale {channel1}"), color=discord.Color.green())
560 await ctx.send(embed=embed, delete_after=20)
561
562 else:
563 ctx.voice_state.voice = await channel1.connect()
564 embed = discord.Embed(title="Fatto!", description=(f"Mi sono connesso al canale {channel1}"), color=discord.Color.green())
565 await ctx.send(embed=embed, delete_after=20)
566
567
568
569 @commands.command(name="leave", aliases=["l"])
570 async def _leave(self, ctx):
571 if ctx.guild.id == 539884642367438888:
572 if not ctx.message.channel.id in canali_musica:
573 embed = discord.Embed(title="Nope", description="Per favore, usa i comandi musicali nell'apposito canale <#693003574468411412>", color=discord.Color.orange())
574 return await ctx.send(embed=embed)
575 else:
576 pass
577
578 voice = get(client.voice_clients, guild=ctx.guild)
579 vc = ctx.voice_client
580 channel1 = ctx.author.voice.channel
581 if vc.channel != channel1:
582 if vc.is_playing() or vc.is_paused():
583 embed = discord.Embed(title="Nope", description="Il bot è già utilizzato da qualcun'altro", color=discord.Color.red())
584 return await ctx.send(embed=embed)
585
586 try:
587 await ctx.voice_client.disconnect()
588 embed = discord.Embed(title="Fatto!", description="Sono uscito dal canale vocale!", color=discord.Color.orange())
589 await ctx.send(embed=embed, delete_after=4)
590 except:
591 embed = discord.Embed(title="No", description="Non sono connesso ad un canale vocale!", color=discord.Color.red())
592 await ctx.send(embed=embed, delete_after=4)
593
594 @commands.command(name='volume', aliases=["vol", "vl", "vlvl"])
595 async def _volume(self, ctx: commands.Context, *, vol):
596 if ctx.guild.id == 539884642367438888:
597 if not ctx.message.channel.id in canali_musica:
598 embed = discord.Embed(title="Nope", description="Per favore, usa i comandi musicali nell'apposito canale <#693003574468411412>", color=discord.Color.orange())
599 return await ctx.send(embed=embed)
600 else:
601 pass
602 if vol == "max":
603 vol = 1.7976931348623157e+308
604
605 else:
606 vol = float(vol)
607
608 vc = ctx.voice_client
609
610 if not vc or not vc.is_connected():
611 embed = discord.Embed(title="No", description="Non sono connesso ad un canale vocale.", color=discord.Color.red())
612 return await ctx.send(embed=embed, delete_after=20)
613
614 channel1 = ctx.author.voice.channel
615 if vc.channel != channel1:
616 if vc.is_playing() or vc.is_paused():
617 embed = discord.Embed(title="Nope", description="Il bot è già utilizzato da qualcun'altro", color=discord.Color.red())
618 return await ctx.send(embed=embed)
619 else:
620 pass
621
622
623 if not 0 < vol < 101:
624 embed = discord.Embed(title="No fottiti", description="Il comando funziona però mi andava di mandarti a farti fottere lmao", color=discord.Color.red())
625 await ctx.send(embed=embed)
626
627 if vc.source:
628 vc.source.volume = vol / 100
629
630 ctx.voice_state.current.source.volume = vol / 100
631 embed = discord.Embed(title="yooooooooooooooooo", description=f"{ctx.author.mention} ha messo il volume al {vol}%", color=discord.Color.orange())
632 await ctx.send(embed=embed)
633
634 @commands.command(name='now', aliases=['current', 'playing', 'np'])
635 async def _now(self, ctx: commands.Context):
636 if ctx.guild.id == 539884642367438888:
637 if not ctx.message.channel.id in canali_musica:
638 embed = discord.Embed(title="Nope", description="Per favore, usa i comandi musicali nell'apposito canale <#693003574468411412>", color=discord.Color.orange())
639 return await ctx.send(embed=embed)
640 else:
641 pass
642
643 """Displays the currently playing song."""
644 musica = ctx.voice_client.source.title
645 try:
646 # Remove our previous now_playing message.
647 await ctx.voice_state.np.delete()
648 except Exception as e:
649 #raise(e)
650 pass
651 np = await ctx.send(embed=ctx.voice_state.current.create_embed())
652
653 ctx.voice_state.np = np
654 @commands.command(name='pause', aliases=["pa", "pausa"])
655 async def _pause(self, ctx: commands.Context):
656 if ctx.guild.id == 539884642367438888:
657 if not ctx.message.channel.id in canali_musica:
658 embed = discord.Embed(title="Nope", description="Per favore, usa i comandi musicali nell'apposito canale <#693003574468411412>", color=discord.Color.orange())
659 return await ctx.send(embed=embed)
660 else:
661 pass
662
663 vc = ctx.voice_client
664
665 channel1 = ctx.author.voice.channel
666 if vc.channel != channel1:
667 if vc.is_playing() or vc.is_paused():
668 embed = discord.Embed(title="Nope", description="Il bot è già utilizzato da qualcun'altro", color=discord.Color.red())
669 return await ctx.send(embed=embed)
670 else:
671 pass
672
673 if not vc or not vc.is_playing():
674 embed = discord.Embed(title="Ma cosa c'è?", description="Non sto suonando nullaaaaaaaaaaaaaaaaaa", color=discord.Color.red())
675 return await ctx.send(embed=embed, delete_after=20)
676 elif vc.is_paused():
677 return
678
679 vc.pause()
680 embed = discord.Embed(title="Oke", description="Fatto, ho stoppato.", color=discord.Color.orange())
681 await ctx.send(embed=embed)
682
683
684 @commands.command(name='resume', aliases=["res"])
685 async def _resume(self, ctx: commands.Context):
686 vc = ctx.voice_client
687 if ctx.guild.id == 539884642367438888:
688 if not ctx.message.channel.id in canali_musica:
689 embed = discord.Embed(title="Nope", description="Per favore, usa i comandi musicali nell'apposito canale <#693003574468411412>", color=discord.Color.orange())
690 return await ctx.send(embed=embed)
691 else:
692 pass
693
694 if not vc or not vc.is_connected():
695 embed = discord.Embed(title="Nup", description="Non c'è nulla in pausa.", color=discord.Color.red())
696 return await ctx.send(embed=embed)
697 elif not vc.is_paused():
698 return
699 channel1 = ctx.author.voice.channel
700 if vc.channel != channel1:
701 if vc.is_playing() or vc.is_paused():
702 embed = discord.Embed(title="Nope", description="Il bot è già utilizzato da qualcun'altro", color=discord.Color.red())
703 return await ctx.send(embed=embed)
704 else:
705 pass
706
707 vc.resume()
708 embed = discord.Embed(title="Fatto", description="Fatto, ho ripreso a suonare.", color=discord.Color.orange())
709 await ctx.send(embed=embed)
710
711 @commands.command(name='stop', aliases=["clear"])
712 async def _stop(self, ctx: commands.Context):
713 if ctx.guild.id == 539884642367438888:
714 if not ctx.message.channel.id in canali_musica:
715 embed = discord.Embed(title="Nope", description="Per favore, usa i comandi musicali nell'apposito canale <#693003574468411412>", color=discord.Color.orange())
716 return await ctx.send(embed=embed)
717 else:
718 pass
719
720 vc = ctx.voice_client
721 if not vc or not vc.is_connected():
722 embed = discord.Embed(title="Mi hai rotto", description="Ora mi spieghi come CAZZO faccio a fermare la musica se non sono nemmeno in un cazzo di canale vocale oh", color=discord.Color.orange())
723 return await ctx.send(embed=embed)
724
725 else:
726 channel1 = ctx.author.voice.channel
727 if vc.channel != channel1:
728 if vc.is_playing() or vc.is_paused():
729 embed = discord.Embed(title="Nope", description="Il bot è già utilizzato da qualcun'altro", color=discord.Color.red())
730 return await ctx.send(embed=embed)
731 else:
732 pass
733
734
735 ctx.voice_state.songs.clear()
736
737 if ctx.voice_state.is_playing:
738 ctx.voice_state.voice.stop()
739 embed = discord.Embed(title="Oke", description="Ok, ho fermato tutto lmao", color=discord.Color.orange())
740 await ctx.send(embed=embed)
741 else:
742 embed = discord.Embed(title="Ma ooooooo ", description="Pagliaccio non sto suonando nulla, che cazzo mi chiami a fare", color=discord.Color.orange())
743 await ctx.send(embed=embed)
744 @commands.command(name='skip', aliases=["s"])
745 async def _skip(self, ctx: commands.Context):
746
747 if ctx.guild.id == 539884642367438888:
748 if not ctx.message.channel.id in canali_musica:
749 embed = discord.Embed(title="Nope", description="Per favore, usa i comandi musicali nell'apposito canale <#693003574468411412>", color=discord.Color.orange())
750 return await ctx.send(embed=embed)
751 else:
752 pass
753
754 vc = ctx.voice_client
755
756 if not vc or not vc.is_connected():
757 embed = discord.Embed(title="Col cazzo", description="Non sono collegato nemmeno a un canale", color=discord.Color.red())
758 return await ctx.send(embed=embed, delete_after=20)
759
760 else:
761 channel1 = ctx.author.voice.channel
762 if vc.channel != channel1:
763 if vc.is_playing() or vc.is_paused():
764 embed = discord.Embed(title="Nope", description="Il bot è già utilizzato da qualcun'altro", color=discord.Color.red())
765 return await ctx.send(embed=embed)
766 else:
767 pass
768
769 if vc.is_paused():
770 embed = discord.Embed(title="Nope", description="La musica è stoppata", color=discord.Color.red())
771 return await ctx.send(embed=embed)
772 elif not vc.is_playing():
773 embed = discord.Embed(title="Col cazzo", description="Non sto suonando nulla, che devo skippare?", color=discord.Color.red())
774 return await ctx.send(embed=embed)
775
776 ctx.voice_state.skip()
777
778 embed = discord.Embed(title="Oke", description=f"{ctx.author.mention} ha skippato", color=discord.Color.orange())
779 await ctx.send(embed=embed, delete_after=10)
780
781
782 @commands.command(name='queue', aliases=["q"])
783 async def _queue(self, ctx: commands.Context, *, page: int = 1):
784 if ctx.guild.id == 539884642367438888:
785 if not ctx.message.channel.id in canali_musica:
786 embed = discord.Embed(title="Nope", description="Per favore, usa i comandi musicali nell'apposito canale <#693003574468411412>", color=discord.Color.orange())
787 return await ctx.send(embed=embed)
788 else:
789 pass
790
791 vc = ctx.voice_client
792
793 if len(ctx.voice_state.songs) == 0:
794 embed = discord.Embed(title="Uhm", description="Non ci sono canzoni in coda.", color=discord.Color.red())
795 return await ctx.send(embed=embed)
796
797 items_per_page = 10
798 pages = math.ceil(len(ctx.voice_state.songs) / items_per_page)
799
800 start = (page - 1) * items_per_page
801 end = start + items_per_page
802
803 queue = ''
804 for i, song in enumerate(ctx.voice_state.songs[start:end], start=start):
805 queue += '{0}) {1.source.title} **[URL]({1.source.url})**\n'.format(i + 1, song)
806
807 embed = discord.Embed(title=f"Ci sono {len(ctx.voice_state.songs)} canzoni in coda!", description=f'''-----------------------------------------
808 **In Riproduzione:** {vc.source.title}
809 -----------------------------------------
810
811 {queue}''', color=discord.Color.orange())
812 embed.set_footer(text=f"Pagina {page}/{pages}")
813
814 await ctx.send(embed=embed)
815
816 @commands.command(name='cambiaordine', aliases=["random"])
817 async def _mischia(self, ctx: commands.Context):
818 if ctx.guild.id == 539884642367438888:
819 if not ctx.message.channel.id in canali_musica:
820 embed = discord.Embed(title="Nope", description="Per favore, usa i comandi musicali nell'apposito canale <#693003574468411412>", color=discord.Color.orange())
821 return await ctx.send(embed=embed)
822 else:
823 pass
824
825 vc = ctx.voice_client
826
827 channel1 = ctx.author.voice.channel
828 if vc.channel != channel1:
829 if vc.is_playing() or vc.is_paused():
830 embed = discord.Embed(title="Nope", description="Il bot è già utilizzato da qualcun'altro", color=discord.Color.red())
831 return await ctx.send(embed=embed)
832 else:
833 pass
834
835 if len(ctx.voice_state.songs) == 0:
836 embed = discord.Embed(title="Uhm", description="Non ci sono canzoni in coda.", color=discord.Color.red())
837 return await ctx.send(embed=embed)
838
839 ctx.voice_state.songs.shuffle()
840 embed = discord.Embed(title="Okeee", description="Ho mischiato l'ordine delle canzoni in coda.", color=discord.Color.orange())
841 await ctx.send(embed=embed)
842
843
844 @commands.command(name='remove', aliases=["rimuovi"])
845 async def _remove(self, ctx: commands.Context, index: int):
846 if ctx.guild.id == 539884642367438888:
847 if not ctx.message.channel.id in canali_musica:
848 embed = discord.Embed(title="Nope", description="Per favore, usa i comandi musicali nell'apposito canale <#693003574468411412>", color=discord.Color.orange())
849 return await ctx.send(embed=embed)
850 else:
851 pass
852
853 vc = ctx.voice_client
854
855 channel1 = ctx.author.voice.channel
856 if vc.channel != channel1:
857 if vc.is_playing() or vc.is_paused():
858 embed = discord.Embed(title="Nope", description="Il bot è già utilizzato da qualcun'altro", color=discord.Color.red())
859 return await ctx.send(embed=embed)
860 else:
861 pass
862
863
864 if len(ctx.voice_state.songs) == 0:
865 embed = discord.Embed(title="Uhm", description="Non ci sono canzoni in coda.", color=discord.Color.red())
866 return await ctx.send(embed=embed)
867
868 ctx.voice_state.songs.remove(index - 1)
869 embed = discord.Embed(title="oke", description=f"Ho rimosso il {index}° brano dalla coda.", color=discord.Color.orange())
870 await ctx.send(embed=embed)
871
872 @commands.command(name='loop')
873 async def _loop(self, ctx: commands.Context):
874 if ctx.guild.id == 539884642367438888:
875 if not ctx.message.channel.id in canali_musica:
876 embed = discord.Embed(title="Nope", description="Per favore, usa i comandi musicali nell'apposito canale <#693003574468411412>", color=discord.Color.orange())
877 return await ctx.send(embed=embed)
878 else:
879 pass
880
881
882 vc = ctx.voice_client
883
884 channel1 = ctx.author.voice.channel
885 if vc.channel != channel1:
886 if vc.is_playing() or vc.is_paused():
887 embed = discord.Embed(title="Nope", description="Il bot è già utilizzato da qualcun'altro", color=discord.Color.red())
888 return await ctx.send(embed=embed)
889 else:
890 pass
891
892 if not ctx.voice_state.is_playing:
893 embed = discord.Embed(title="Ok", description="Provaci tu a loopare il nulla ;_;", color=discord.Color.red())
894 return await ctx.send(embed=embed)
895
896 # Inverse boolean value to loop and unloop.
897 ctx.voice_state.loop = not ctx.voice_state.loop
898 if ctx.voice_state.loop == True:
899 embed = discord.Embed(title="Oke", description="Sto loopando la canzone", color=discord.Color.orange())
900 await ctx.send(embed=embed)
901 if ctx.voice_state.loop == False:
902 embed = discord.Embed(title="Oke", description="Non sto loopando la canzone", color=discord.Color.orange())
903 await ctx.send(embed=embed)
904 @commands.command(name='play', aliases=["p"])
905 async def _play(self, ctx, *, search: str):
906 if ctx.guild.id == 539884642367438888:
907 if not ctx.message.channel.id in canali_musica:
908 embed = discord.Embed(title="Nope", description="Per favore, usa i comandi musicali nell'apposito canale <#693003574468411412>", color=discord.Color.orange())
909 return await ctx.send(embed=embed)
910 else:
911 pass
912
913 vc = ctx.voice_client
914
915 if not vc or vc.channel.id != ctx.author.voice.channel.id:
916 await ctx.invoke(self._join)
917
918
919
920 async with ctx.typing():
921 if "https://open.spotify.com/playlist/" in search:
922 pass
923 try:
924 source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop)
925 except YTDLError as e:
926 await ctx.send('Errore: {}'.format(str(e)))
927 else:
928 song = Song(source)
929
930 await ctx.voice_state.songs.put(song)
931
932 try:
933 ciao = vc.source.title
934 embed = discord.Embed(title="Oke", description=f"Ho aggiunto {str(source)} alla coda.", color=discord.Color.orange())
935 await ctx.send(embed=embed)
936 except AttributeError:
937 return
938
939 @commands.command(name='search', aliases=["plai"])
940 async def _search(self, ctx: commands.Context, *, search: str):
941 """Searches youtube.
942 It returns an imbed of the first 10 results collected from youtube.
943 Then the user can choose one of the titles by typing a number
944 in chat or they can cancel by typing "cancel" in chat.
945 Each title in the list can be clicked as a link.
946 """
947 if ctx.guild.id == 539884642367438888:
948 if not ctx.message.channel.id in canali_musica:
949 embed = discord.Embed(title="Nope", description="Per favore, usa i comandi musicali nell'apposito canale <#693003574468411412>", color=discord.Color.orange())
950 return await ctx.send(embed=embed)
951 else:
952 pass
953
954 vc = ctx.voice_client
955
956 async with ctx.typing():
957 try:
958 source = await YTDLSource.search_source(ctx, search, loop=self.bot.loop)
959 except YTDLError as e:
960 await ctx.send('Fratellì, c\'è stato un errore: {}'.format(str(e)))
961 else:
962 if source == 'sel_invalid':
963 embed = discord.Embed(title="Ma che caz", description="Che numero hai scelto? Noccapito", color=discord.Color.orange())
964 await ctx.send(embed=embed)
965 elif source == 'cancel':
966 embed = discord.Embed(title="Apposto fratellì", description="Ho cancellato tutto fratellì", color=discord.Color.orange())
967 await ctx.send(embed=embed)
968 elif source == 'timeout':
969 embed = discord.Embed(title="Eh mi spiace", description=':alarm_clock: **Tempo scaduto fratellì**', color=discord.Color.orange())
970 await ctx.send(embed=embed)
971 else:
972 if not ctx.voice_state.voice:
973 await ctx.invoke(self._join)
974
975 song = Song(source)
976
977 await ctx.voice_state.songs.put(song)
978 try:
979 ciao = vc.source.title
980 embed = discord.Embed(title="Oke", description=f"Ho aggiunto {str(source)} alla coda.", color=discord.Color.orange())
981 await ctx.send(embed=embed)
982 except AttributeError:
983 return
984 @commands.command(name="lyrics")
985 async def lyrics(self, ctx, * , musica=None):
986 if not ctx.channel.id in canali_musica:
987 embed = discord.Embed(title="Nope", description="Per favore, usa i comandi musicali nell'apposito canale <#693003574468411412>", color=discord.Color.orange())
988 return await ctx.send(embed=embed)
989 await lyricsdef(ctx, musica)
990
991
992
993
994 @commands.command(name='spotify')
995 async def _spotify(self, ctx, *, nick_name: discord.Member=None):
996
997 guild = ctx.guild
998
999 spotify_member = None
1000 if not nick_name:
1001 spotify_member = ctx.message.author
1002
1003
1004 else:
1005 nome = nick_name.name
1006 tag = nick_name.discriminator
1007 fine = f"{nome}#{tag}"
1008 spotify_member = await commands.MemberConverter().convert(ctx, fine)
1009
1010
1011
1012 if spotify_member is None:
1013 embed = discord.Embed(title="Ou", description="Noccapito l'utente a cui devo copiare", color=discord.Color.orange())
1014 return await ctx.send(embed=embed)
1015 if spotify_member.activity.name != "Spotify":
1016 embed = discord.Embed(title="Fratellì", description="Devi avere spotify nell'attività di gioco, o almeno ascoltare la musica", color=discord.Color.orange())
1017 return await ctx.send(embed=embed)
1018
1019
1020 search = spotify_member.activity.title + " " + spotify_member.activity.artist
1021
1022
1023
1024 embed = discord.Embed(title="Ecco qua!", description=f'''L'utente **<@{ctx.author.id}>** sta ascoltando:''', color=discord.Color.orange())
1025 embed.add_field(name="Titolo", value=spotify_member.activity.title, inline=True)
1026 embed.add_field(name="Artista", value=spotify_member.activity.artist)
1027
1028 await ctx.send(embed=embed)
1029
1030 embed1 = discord.Embed(title="Che vuoi fare?", color=discord.Color.orange())
1031 embed1.add_field(name="Per non fare nulla", value="❌", inline=True)
1032 embed1.add_field(name="Per la lyrics", value="?️", inline=True)
1033 embed1.add_field(name="\u200b", value="\u200b", inline=True)
1034 embed1.add_field(name="Per suonarla", value="▶️", inline=True)
1035 embed1.add_field(name="Per suonarla, e la lyrics", value="✅", inline=True)
1036 embed1.add_field(name="\u200b", value="\u200b", inline=True)
1037
1038 message = await ctx.send(embed=embed1)
1039
1040 x = str("❌")
1041 a = str("?️")
1042 play = str("▶️")
1043 playandlyrics = str("✅")
1044
1045 await message.add_reaction(x)
1046 await message.add_reaction(a)
1047 await message.add_reaction(play)
1048 await message.add_reaction(playandlyrics)
1049
1050 channel = ctx.channel
1051 author = ctx.author
1052
1053 async def suona(ctx, search):
1054 vc = ctx.voice_client
1055
1056 if not vc or vc.channel.id != ctx.author.voice.channel.id:
1057 await ctx.invoke(self._join)
1058
1059
1060
1061 async with ctx.typing():
1062 try:
1063 source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop)
1064 except YTDLError as e:
1065 await ctx.send('Errore: {}'.format(str(e)))
1066 else:
1067 song = Song(source)
1068
1069 await ctx.voice_state.songs.put(song)
1070
1071 try:
1072 ciao = vc.source.title
1073 embed = discord.Embed(title="Oke", description=f"Ho aggiunto {str(source)} alla coda.", color=discord.Color.orange())
1074 await ctx.send(embed=embed)
1075 except AttributeError:
1076 return
1077 channel = ctx.channel
1078 author = ctx.author
1079
1080 def predicate(message):
1081 def check(reaction, user):
1082 if reaction.message.id != message.id or user == client.user:
1083 return False
1084 if user == author and reaction.message.channel == channel:
1085 return True
1086 return check
1087
1088
1089
1090 reaction, user = await ctx.bot.wait_for('reaction_add', check=predicate(message))
1091
1092 if reaction.emoji == x:
1093 embed = discord.Embed(title="Ok", description="Non succederà nulla.", color=discord.Color.orange())
1094 return await ctx.send(embed=embed, delete_after=4)
1095
1096 elif reaction.emoji == a:
1097 embed = discord.Embed(title="Ok", description="Ecco la lyrics", color=discord.Color.orange())
1098 await ctx.send(embed=embed)
1099
1100 await lyricsdef(ctx, search)
1101
1102
1103 elif reaction.emoji == play:
1104 embed = discord.Embed(title="Ok", description="Ok la suono.", color=discord.Color.orange())
1105 await ctx.send(embed=embed)
1106
1107 await suona(ctx, search)
1108
1109 elif reaction.emoji == playandlyrics:
1110
1111 embed = discord.Embed(title="Ok", description="Ecco la lyrics e la canzone.", color=discord.Color.orange())
1112 await ctx.send(embed=embed)
1113
1114 await suona(ctx, search)
1115
1116 await lyricsdef(ctx, search)
1117 await asyncio.sleep(1.4)
1118 await message.delete()
1119 # @commands.Cog.listener()
1120 # async def on_voice_state_update(self, member, before, after):
1121 # afk = client.get_channel(688286341812977805)
1122 # guild = member.guild
1123 # afk1 = guild.get_role(713464440665669702)
1124
1125 # if member.voice:
1126 # if before.channel == afk and after.channel != afk or member.voice.channel == None:
1127 # await member.remove_roles(afk1)
1128 # elif member.voice.channel == afk:
1129 # await member.add_roles(afk1)
1130
1131 # if before.channel is None and after.channel != None:
1132 # if member.bot:
1133 # return
1134
1135 # marino = 427065443325313037
1136 # turco = 571440707404038146
1137 # arnoldo = 454658813237395458
1138 # pace = 425400829823156235
1139 # salvo = 685760749527760896
1140 # async def suona()
1141
1142
1143
1144 @_join.before_invoke
1145 @_play.before_invoke
1146 async def ensure_voice_state(self, ctx: commands.Context):
1147 vc = ctx.voice_client
1148
1149 if ctx.voice_client:
1150 if vc.is_playing() or vc.is_paused():
1151 if ctx.voice_client.channel != ctx.author.voice.channel:
1152 embed = discord.Embed(title="Nope", description="Il bot è già utilizzato da qualcun'altro", color=discord.Color.red())
1153 return await ctx.send(embed=embed)
1154
1155
1156
1157
1158
1159
1160 def setup(client):
1161 client.add_cog(Music(client))
1162
1163 client.add_cog(Music(client))
1164
1165 token = open("token.txt", "r").read()
1166 client.run(token)
1167except Exception as e:
1168 raise(e)