mirror of
https://github.com/deadcxap/YandexMusicDiscordBot.git
synced 2026-01-12 07:11:40 +03:00
impr: Add player repeat and shuffle, play artist and playlist. Code optimization.
This commit is contained in:
@@ -1,11 +1,12 @@
|
||||
from os import getenv
|
||||
from math import ceil
|
||||
from typing import cast
|
||||
|
||||
import discord
|
||||
from yandex_music import Track, Album, Artist, Label
|
||||
from yandex_music import Track, Album, Artist, Playlist, Label
|
||||
|
||||
from discord.ui import View, Button, Item
|
||||
from discord import ButtonStyle, Interaction
|
||||
from discord import ButtonStyle, Interaction, Embed
|
||||
|
||||
from MusicBot.cogs.utils.voice import VoiceExtension, get_average_color_from_url
|
||||
|
||||
@@ -19,20 +20,22 @@ class PlayTrackButton(Button, VoiceExtension):
|
||||
async def callback(self, interaction: Interaction) -> None:
|
||||
if not interaction.guild or not await self.voice_check(interaction):
|
||||
return
|
||||
|
||||
gid = interaction.guild.id
|
||||
guild = self.db.get_guild(gid)
|
||||
|
||||
if guild['current_track'] is not None:
|
||||
|
||||
if guild['current_track']:
|
||||
self.db.modify_track(gid, self.track, 'next', 'append')
|
||||
if guild['current_player'] is not None and interaction.message:
|
||||
await interaction.message.delete()
|
||||
await interaction.respond(f"Трек **{self.track.title}** был добавлен в очередь.", delete_after=15)
|
||||
response_message = f"Трек **{self.track.title}** был добавлен в очередь."
|
||||
else:
|
||||
title = await self.play_track(interaction, self.track)
|
||||
if title:
|
||||
if guild['current_player'] is not None and interaction.message:
|
||||
await interaction.message.delete()
|
||||
await interaction.respond(f"Сейчас играет: **{title}**!", delete_after=15)
|
||||
await self.play_track(interaction, self.track)
|
||||
response_message = f"Сейчас играет: **{self.track.title}**!"
|
||||
|
||||
if guild['current_player'] is not None and interaction.message:
|
||||
await interaction.message.delete()
|
||||
|
||||
await interaction.respond(response_message, delete_after=15)
|
||||
|
||||
|
||||
class PlayAlbumButton(Button, VoiceExtension):
|
||||
|
||||
@@ -44,152 +47,149 @@ class PlayAlbumButton(Button, VoiceExtension):
|
||||
async def callback(self, interaction: Interaction) -> None:
|
||||
if not interaction.guild or not await self.voice_check(interaction):
|
||||
return
|
||||
gid = interaction.guild.id
|
||||
guild = self.db.get_guild(gid)
|
||||
|
||||
|
||||
album = await self.album.with_tracks_async()
|
||||
if not album or not album.volumes:
|
||||
return
|
||||
|
||||
tracks: list[Track] = []
|
||||
for volume in album.volumes:
|
||||
tracks.extend(volume)
|
||||
|
||||
|
||||
gid = interaction.guild.id
|
||||
guild = self.db.get_guild(gid)
|
||||
|
||||
tracks: list[Track] = [track for volume in album.volumes for track in volume]
|
||||
|
||||
if guild['current_track'] is not None:
|
||||
self.db.modify_track(gid, tracks, 'next', 'extend')
|
||||
if guild['current_player'] is not None and interaction.message:
|
||||
await interaction.message.delete()
|
||||
else:
|
||||
await interaction.respond(f"Альбом **{album.title}** был добавлен в очередь.", delete_after=15)
|
||||
response_message = f"Альбом **{album.title}** был добавлен в очередь."
|
||||
else:
|
||||
track = tracks.pop(0)
|
||||
self.db.modify_track(gid, tracks, 'next', 'extend')
|
||||
await self.play_track(interaction, track)
|
||||
response_message = f"Сейчас играет: **{album.title}**!"
|
||||
|
||||
title = await self.play_track(interaction, track)
|
||||
if title:
|
||||
if guild['current_player'] is not None and interaction.message:
|
||||
await interaction.message.delete()
|
||||
else:
|
||||
await interaction.respond(f"Сейчас играет: **{album.title}**!", delete_after=15)
|
||||
if guild['current_player'] is not None and interaction.message:
|
||||
await interaction.message.delete()
|
||||
else:
|
||||
await interaction.respond(response_message, delete_after=15)
|
||||
|
||||
|
||||
class PlayArtistButton(Button, VoiceExtension):
|
||||
def __init__(self, artist: Artist, **kwargs):
|
||||
Button.__init__(self, **kwargs)
|
||||
VoiceExtension.__init__(self)
|
||||
self.artist = artist
|
||||
|
||||
async def callback(self, interaction: Interaction) -> None:
|
||||
if not interaction.guild or not await self.voice_check(interaction):
|
||||
return
|
||||
|
||||
artist_tracks = await self.artist.get_tracks_async(page_size=500)
|
||||
if not artist_tracks:
|
||||
return
|
||||
|
||||
gid = interaction.guild.id
|
||||
guild = self.db.get_guild(gid)
|
||||
|
||||
tracks: list[Track] = artist_tracks.tracks
|
||||
|
||||
if guild['current_track'] is not None:
|
||||
self.db.modify_track(gid, tracks, 'next', 'extend')
|
||||
response_message = f"Песни артиста **{self.artist.name}** были добавлены в очередь."
|
||||
else:
|
||||
track = tracks.pop(0)
|
||||
self.db.modify_track(gid, tracks, 'next', 'extend')
|
||||
await self.play_track(interaction, track)
|
||||
response_message = f"Сейчас играет: **{self.artist.name}**!"
|
||||
|
||||
if guild['current_player'] is not None and interaction.message:
|
||||
await interaction.message.delete()
|
||||
|
||||
await interaction.respond(response_message, delete_after=15)
|
||||
|
||||
class PlayPlaylistButton(Button, VoiceExtension):
|
||||
def __init__(self, playlist: Playlist, **kwargs):
|
||||
Button.__init__(self, **kwargs)
|
||||
VoiceExtension.__init__(self)
|
||||
self.playlist = playlist
|
||||
|
||||
async def callback(self, interaction: Interaction) -> None:
|
||||
if not interaction.guild or not await self.voice_check(interaction):
|
||||
return
|
||||
|
||||
short_tracks = await self.playlist.fetch_tracks_async()
|
||||
if not short_tracks:
|
||||
return
|
||||
|
||||
gid = interaction.guild.id
|
||||
guild = self.db.get_guild(gid)
|
||||
|
||||
tracks: list[Track] = [cast(Track, short_track.track) for short_track in short_tracks]
|
||||
|
||||
if guild['current_track'] is not None:
|
||||
self.db.modify_track(gid, tracks, 'next', 'extend')
|
||||
response_message = f"Плейлист **{self.playlist.title}** был добавлен в очередь."
|
||||
else:
|
||||
track = tracks.pop(0)
|
||||
self.db.modify_track(gid, tracks, 'next', 'extend')
|
||||
await self.play_track(interaction, track)
|
||||
response_message = f"Сейчас играет: **{self.playlist.title}**!"
|
||||
|
||||
if guild['current_player'] is not None and interaction.message:
|
||||
await interaction.message.delete()
|
||||
|
||||
await interaction.respond(response_message, delete_after=15)
|
||||
|
||||
class ListenTrack(View):
|
||||
|
||||
def __init__(self, track: Track, album_id: int, *items: Item, timeout: float | None = 360, disable_on_timeout: bool = True):
|
||||
def __init__(self, track: Track, album_id: int, *items: Item, timeout: float | None = None, disable_on_timeout: bool = False):
|
||||
super().__init__(*items, timeout=timeout, disable_on_timeout=disable_on_timeout)
|
||||
link_app = f"yandexmusic://album/{album_id}/track/{track.id}"
|
||||
link_web = f"https://music.yandex.ru/album/{album_id}/track/{track.id}"
|
||||
self.button1 = Button(label="Слушать в приложении", style=ButtonStyle.gray, url=link_app)
|
||||
self.button2 = Button(label="Слушать в браузере", style=ButtonStyle.gray, url=link_web)
|
||||
self.button3 = PlayTrackButton(track, label="Слушать в голосовом канале", style=ButtonStyle.gray)
|
||||
self.button1: Button = Button(label="Слушать в приложении", style=ButtonStyle.gray, url=link_app)
|
||||
self.button2: Button = Button(label="Слушать в браузере", style=ButtonStyle.gray, url=link_web)
|
||||
self.button3: PlayTrackButton = PlayTrackButton(track, label="Слушать в голосовом канале", style=ButtonStyle.gray)
|
||||
# self.add_item(self.button1) # Discord doesn't allow well formed URLs in buttons for some reason.
|
||||
self.add_item(self.button2)
|
||||
self.add_item(self.button3)
|
||||
|
||||
class ListenAlbum(View):
|
||||
|
||||
def __init__(self, album: Album, *items: Item, timeout: float | None = 360, disable_on_timeout: bool = True):
|
||||
def __init__(self, album: Album, *items: Item, timeout: float | None = None, disable_on_timeout: bool = False):
|
||||
super().__init__(*items, timeout=timeout, disable_on_timeout=disable_on_timeout)
|
||||
link_app = f"yandexmusic://album/{album.id}"
|
||||
link_web = f"https://music.yandex.ru/album/{album.id}"
|
||||
self.button1 = Button(label="Слушать в приложении", style=ButtonStyle.gray, url=link_app)
|
||||
self.button2 = Button(label="Слушать в браузере", style=ButtonStyle.gray, url=link_web)
|
||||
self.button3 = PlayAlbumButton(album, label="Слушать в голосовом канале", style=ButtonStyle.gray)
|
||||
self.button1: Button = Button(label="Слушать в приложении", style=ButtonStyle.gray, url=link_app)
|
||||
self.button2: Button = Button(label="Слушать в браузере", style=ButtonStyle.gray, url=link_web)
|
||||
self.button3: PlayAlbumButton = PlayAlbumButton(album, label="Слушать в голосовом канале", style=ButtonStyle.gray)
|
||||
# self.add_item(self.button1) # Discord doesn't allow well formed URLs in buttons for some reason.
|
||||
self.add_item(self.button2)
|
||||
self.add_item(self.button3)
|
||||
|
||||
class ListenArtist(View):
|
||||
|
||||
def __init__(self, artist_id: int, *items: Item, timeout: float | None = 360, disable_on_timeout: bool = True):
|
||||
def __init__(self, artist: Artist, *items: Item, timeout: float | None = None, disable_on_timeout: bool = False):
|
||||
super().__init__(*items, timeout=timeout, disable_on_timeout=disable_on_timeout)
|
||||
link_app = f"yandexmusic://artist/{artist_id}"
|
||||
link_web = f"https://music.yandex.ru/artist/{artist_id}"
|
||||
self.button1 = Button(label="Слушать в приложении", style=ButtonStyle.gray, url=link_app)
|
||||
self.button2 = Button(label="Слушать в браузере", style=ButtonStyle.gray, url=link_web)
|
||||
link_app = f"yandexmusic://artist/{artist.id}"
|
||||
link_web = f"https://music.yandex.ru/artist/{artist.id}"
|
||||
self.button1: Button = Button(label="Слушать в приложении", style=ButtonStyle.gray, url=link_app)
|
||||
self.button2: Button = Button(label="Слушать в браузере", style=ButtonStyle.gray, url=link_web)
|
||||
self.button3: PlayArtistButton = PlayArtistButton(artist, label="Слушать в голосовом канале", style=ButtonStyle.gray)
|
||||
# self.add_item(self.button1) # Discord doesn't allow well formed URLs in buttons for some reason.
|
||||
self.add_item(self.button2)
|
||||
self.add_item(self.button3)
|
||||
|
||||
class ListenPlaylist(View):
|
||||
def __init__(self, playlist: Playlist, *items: Item, timeout: float | None = None, disable_on_timeout: bool = False):
|
||||
super().__init__(*items, timeout=timeout, disable_on_timeout=disable_on_timeout)
|
||||
link_app = f"yandexmusic://playlist/{playlist.playlist_uuid}"
|
||||
link_web = f"https://music.yandex.ru/playlist/{playlist.playlist_uuid}"
|
||||
self.button1: Button = Button(label="Слушать в приложении", style=ButtonStyle.gray, url=link_app)
|
||||
self.button2: Button = Button(label="Слушать в браузере", style=ButtonStyle.gray, url=link_web)
|
||||
self.button3: PlayPlaylistButton = PlayPlaylistButton(playlist, label="Слушать в голосовом канале", style=ButtonStyle.gray)
|
||||
# self.add_item(self.button1) # Discord doesn't allow well formed URLs in buttons for some reason.
|
||||
self.add_item(self.button2)
|
||||
self.add_item(self.button3)
|
||||
|
||||
async def proccess_album(album: Album) -> discord.Embed:
|
||||
"""Generate album embed.
|
||||
|
||||
Args:
|
||||
album (yandex_music.Album): Album to process.
|
||||
|
||||
Returns:
|
||||
discord.Embed: Album embed.
|
||||
"""
|
||||
|
||||
title = cast(str, album.title)
|
||||
track_count = album.track_count
|
||||
artists = album.artists_name()
|
||||
avail = cast(bool, album.available)
|
||||
description = album.short_description
|
||||
year = album.year
|
||||
version = album.version
|
||||
bests = album.bests
|
||||
duration = album.duration_ms
|
||||
explicit = album.explicit or album.content_warning
|
||||
likes_count = album.likes_count
|
||||
artist = album.artists[0]
|
||||
|
||||
cover_url = album.get_cover_url('400x400')
|
||||
color = await get_average_color_from_url(cover_url)
|
||||
|
||||
if isinstance(album.labels[0], Label):
|
||||
labels = [cast(Label, label).name for label in album.labels]
|
||||
else:
|
||||
labels = [cast(str, label) for label in album.labels]
|
||||
|
||||
if version:
|
||||
title += f' *{version}*'
|
||||
|
||||
if explicit:
|
||||
title += ' <:explicit:1325879701117472869>'
|
||||
|
||||
artist_url = f"https://music.yandex.ru/artist/{artist.id}"
|
||||
artist_cover = artist.cover
|
||||
if not artist_cover:
|
||||
artist_cover_url = artist.get_op_image_url()
|
||||
else:
|
||||
artist_cover_url = artist_cover.get_url()
|
||||
|
||||
embed = discord.Embed(
|
||||
title=title,
|
||||
description=description,
|
||||
color=color,
|
||||
)
|
||||
embed.set_thumbnail(url=cover_url)
|
||||
embed.set_author(name=", ".join(artists), url=artist_url, icon_url=artist_cover_url)
|
||||
|
||||
if year:
|
||||
embed.add_field(name="Год выпуска", value=str(year))
|
||||
|
||||
if duration:
|
||||
duration_m = duration // 60000
|
||||
duration_s = ceil(duration / 1000) - duration_m * 60
|
||||
embed.add_field(name="Длительность", value=f"{duration_m}:{duration_s:02}")
|
||||
|
||||
if track_count is not None:
|
||||
if track_count > 1:
|
||||
embed.add_field(name="Треки", value=str(track_count))
|
||||
else:
|
||||
embed.add_field(name="Треки", value="Сингл")
|
||||
|
||||
if likes_count:
|
||||
embed.add_field(name="Лайки", value=str(likes_count))
|
||||
|
||||
if len(labels) > 1:
|
||||
embed.add_field(name="Лейблы", value=", ".join(labels))
|
||||
else:
|
||||
embed.add_field(name="Лейбл", value=", ".join(labels))
|
||||
|
||||
if not avail:
|
||||
embed.set_footer(text=f"Трек в данный момент недоступен.")
|
||||
|
||||
return embed
|
||||
|
||||
async def process_track(track: Track) -> discord.Embed:
|
||||
async def process_track(track: Track) -> Embed:
|
||||
"""Generate track embed.
|
||||
|
||||
Args:
|
||||
@@ -215,7 +215,10 @@ async def process_track(track: Track) -> discord.Embed:
|
||||
color = await get_average_color_from_url(cover_url)
|
||||
|
||||
if explicit:
|
||||
title += ' <:explicit:1325879701117472869>'
|
||||
explicit_eid = getenv('EXPLICIT_EID')
|
||||
if not explicit_eid:
|
||||
raise ValueError('You must specify explicit emoji id in your enviroment (EXPLICIT_EID).')
|
||||
title += ' <:explicit:' + explicit_eid + '>'
|
||||
|
||||
duration_m = duration // 60000
|
||||
duration_s = ceil(duration / 1000) - duration_m * 60
|
||||
@@ -262,7 +265,89 @@ async def process_track(track: Track) -> discord.Embed:
|
||||
|
||||
return embed
|
||||
|
||||
async def process_artist(artist: Artist) -> discord.Embed:
|
||||
async def process_album(album: Album) -> Embed:
|
||||
"""Generate album embed.
|
||||
|
||||
Args:
|
||||
album (yandex_music.Album): Album to process.
|
||||
|
||||
Returns:
|
||||
discord.Embed: Album embed.
|
||||
"""
|
||||
|
||||
title = cast(str, album.title)
|
||||
track_count = album.track_count
|
||||
artists = album.artists_name()
|
||||
avail = cast(bool, album.available)
|
||||
description = album.short_description
|
||||
year = album.year
|
||||
version = album.version
|
||||
bests = album.bests
|
||||
duration = album.duration_ms
|
||||
explicit = album.explicit or album.content_warning
|
||||
likes_count = album.likes_count
|
||||
artist = album.artists[0]
|
||||
|
||||
cover_url = album.get_cover_url('400x400')
|
||||
color = await get_average_color_from_url(cover_url)
|
||||
|
||||
if isinstance(album.labels[0], Label):
|
||||
labels = [cast(Label, label).name for label in album.labels]
|
||||
else:
|
||||
labels = [cast(str, label) for label in album.labels]
|
||||
|
||||
if version:
|
||||
title += f' *{version}*'
|
||||
|
||||
if explicit:
|
||||
explicit_eid = getenv('EXPLICIT_EID')
|
||||
if not explicit_eid:
|
||||
raise ValueError('You must specify explicit emoji id in your enviroment.')
|
||||
title += ' <:explicit:' + explicit_eid + '>'
|
||||
|
||||
artist_url = f"https://music.yandex.ru/artist/{artist.id}"
|
||||
artist_cover = artist.cover
|
||||
if not artist_cover:
|
||||
artist_cover_url = artist.get_op_image_url()
|
||||
else:
|
||||
artist_cover_url = artist_cover.get_url()
|
||||
|
||||
embed = discord.Embed(
|
||||
title=title,
|
||||
description=description,
|
||||
color=color,
|
||||
)
|
||||
embed.set_thumbnail(url=cover_url)
|
||||
embed.set_author(name=", ".join(artists), url=artist_url, icon_url=artist_cover_url)
|
||||
|
||||
if year:
|
||||
embed.add_field(name="Год выпуска", value=str(year))
|
||||
|
||||
if duration:
|
||||
duration_m = duration // 60000
|
||||
duration_s = ceil(duration / 1000) - duration_m * 60
|
||||
embed.add_field(name="Длительность", value=f"{duration_m}:{duration_s:02}")
|
||||
|
||||
if track_count is not None:
|
||||
if track_count > 1:
|
||||
embed.add_field(name="Треки", value=str(track_count))
|
||||
else:
|
||||
embed.add_field(name="Треки", value="Сингл")
|
||||
|
||||
if likes_count:
|
||||
embed.add_field(name="Лайки", value=str(likes_count))
|
||||
|
||||
if len(labels) > 1:
|
||||
embed.add_field(name="Лейблы", value=", ".join(labels))
|
||||
else:
|
||||
embed.add_field(name="Лейбл", value=", ".join(labels))
|
||||
|
||||
if not avail:
|
||||
embed.set_footer(text=f"Альбом в данный момент недоступен.")
|
||||
|
||||
return embed
|
||||
|
||||
async def process_artist(artist: Artist) -> Embed:
|
||||
"""Generate artist embed.
|
||||
|
||||
Args:
|
||||
@@ -314,4 +399,55 @@ async def process_artist(artist: Artist) -> discord.Embed:
|
||||
if not avail:
|
||||
embed.set_footer(text=f"Артист в данный момент недоступен.")
|
||||
|
||||
return embed
|
||||
|
||||
async def process_playlist(playlist: Playlist) -> Embed:
|
||||
"""Generate playlist embed.
|
||||
|
||||
Args:
|
||||
playlist (yandex_music.Playlist): Playlist to process.
|
||||
|
||||
Returns:
|
||||
discord.Embed: Playlist embed.
|
||||
"""
|
||||
|
||||
title = cast(str, playlist.title)
|
||||
track_count = playlist.track_count
|
||||
avail = cast(bool, playlist.available)
|
||||
description = playlist.description_formatted
|
||||
year = playlist.created
|
||||
modified = playlist.modified
|
||||
duration = playlist.duration_ms
|
||||
likes_count = playlist.likes_count
|
||||
|
||||
cover_url = f"https://{playlist.cover.uri.replace('%%', '400x400')}" # type: ignore
|
||||
color = await get_average_color_from_url(cover_url)
|
||||
|
||||
embed = discord.Embed(
|
||||
title=title,
|
||||
description=description,
|
||||
color=color,
|
||||
)
|
||||
embed.set_thumbnail(url=cover_url)
|
||||
|
||||
if year:
|
||||
embed.add_field(name="Год создания", value=str(year).split('-')[0])
|
||||
|
||||
if modified:
|
||||
embed.add_field(name="Изменён", value=str(modified).split('-')[0])
|
||||
|
||||
if duration:
|
||||
duration_m = duration // 60000
|
||||
duration_s = ceil(duration / 1000) - duration_m * 60
|
||||
embed.add_field(name="Длительность", value=f"{duration_m}:{duration_s:02}")
|
||||
|
||||
if track_count is not None:
|
||||
embed.add_field(name="Треки", value=str(track_count))
|
||||
|
||||
if likes_count:
|
||||
embed.add_field(name="Лайки", value=str(likes_count))
|
||||
|
||||
if not avail:
|
||||
embed.set_footer(text=f"Плейлист в данный момент недоступен.")
|
||||
|
||||
return embed
|
||||
@@ -1,8 +1,34 @@
|
||||
from discord.ui import View, Button, Item
|
||||
from discord import InteractionMessage, ButtonStyle, Interaction, ApplicationContext
|
||||
from discord import ButtonStyle, Interaction, ApplicationContext
|
||||
|
||||
from MusicBot.cogs.utils.voice import VoiceExtension
|
||||
|
||||
class ToggleRepeatButton(Button, VoiceExtension):
|
||||
def __init__(self, **kwargs):
|
||||
Button.__init__(self, **kwargs)
|
||||
VoiceExtension.__init__(self)
|
||||
|
||||
async def callback(self, interaction: Interaction) -> None:
|
||||
if not interaction.guild:
|
||||
return
|
||||
gid = interaction.guild.id
|
||||
guild = self.db.get_guild(gid)
|
||||
self.db.update(gid, {'repeat': not guild['repeat']})
|
||||
await interaction.edit(view=Player(interaction))
|
||||
|
||||
class ToggleShuffleButton(Button, VoiceExtension):
|
||||
def __init__(self, **kwargs):
|
||||
Button.__init__(self, **kwargs)
|
||||
VoiceExtension.__init__(self)
|
||||
|
||||
async def callback(self, interaction: Interaction) -> None:
|
||||
if not interaction.guild:
|
||||
return
|
||||
gid = interaction.guild.id
|
||||
guild = self.db.get_guild(gid)
|
||||
self.db.update(gid, {'shuffle': not guild['shuffle']})
|
||||
await interaction.edit(view=Player(interaction))
|
||||
|
||||
class PlayPauseButton(Button, VoiceExtension):
|
||||
def __init__(self, **kwargs):
|
||||
Button.__init__(self, **kwargs)
|
||||
@@ -11,24 +37,21 @@ class PlayPauseButton(Button, VoiceExtension):
|
||||
async def callback(self, interaction: Interaction) -> None:
|
||||
if not await self.voice_check(interaction):
|
||||
return
|
||||
|
||||
vc = self.get_voice_client(interaction)
|
||||
if vc is not None:
|
||||
if not vc.is_paused():
|
||||
vc.pause()
|
||||
message = interaction.message
|
||||
if not message:
|
||||
return
|
||||
embed = message.embeds[0]
|
||||
embed.set_footer(text='Приостановлено')
|
||||
await interaction.edit(embed=embed)
|
||||
else:
|
||||
vc.resume()
|
||||
message = interaction.message
|
||||
if not message:
|
||||
return
|
||||
embed = message.embeds[0]
|
||||
embed.remove_footer()
|
||||
await interaction.edit(embed=embed)
|
||||
if not vc or not interaction.message:
|
||||
return
|
||||
|
||||
embed = interaction.message.embeds[0]
|
||||
|
||||
if vc.is_paused():
|
||||
vc.resume()
|
||||
embed.remove_footer()
|
||||
else:
|
||||
vc.pause()
|
||||
embed.set_footer(text='Приостановлено')
|
||||
|
||||
await interaction.edit(embed=embed)
|
||||
|
||||
class NextTrackButton(Button, VoiceExtension):
|
||||
def __init__(self, **kwargs):
|
||||
@@ -54,24 +77,41 @@ class PrevTrackButton(Button, VoiceExtension):
|
||||
if not title:
|
||||
await interaction.respond(f"Нет треков в истории.", delete_after=15, ephemeral=True)
|
||||
|
||||
class Player(View):
|
||||
class Player(View, VoiceExtension):
|
||||
|
||||
def __init__(self, ctx: ApplicationContext, *items: Item, timeout: float | None = 3600, disable_on_timeout: bool = True):
|
||||
super().__init__(*items, timeout=timeout, disable_on_timeout=disable_on_timeout)
|
||||
def __init__(self, ctx: ApplicationContext | Interaction, *items: Item, timeout: float | None = 3600, disable_on_timeout: bool = True):
|
||||
View.__init__(self, *items, timeout=timeout, disable_on_timeout=disable_on_timeout)
|
||||
VoiceExtension.__init__(self)
|
||||
if not ctx.guild:
|
||||
return
|
||||
guild = self.db.get_guild(ctx.guild.id)
|
||||
|
||||
self.ctx = ctx
|
||||
|
||||
self.repeat_button = Button(style=ButtonStyle.secondary, emoji='🔂', row=0)
|
||||
self.shuffle_button = Button(style=ButtonStyle.secondary, emoji='🔀', row=0)
|
||||
self.repeat_button_off = ToggleRepeatButton(style=ButtonStyle.secondary, emoji='🔂', row=0)
|
||||
self.repeat_button_on = ToggleRepeatButton(style=ButtonStyle.success, emoji='🔂', row=0)
|
||||
|
||||
self.shuffle_button_off = ToggleShuffleButton(style=ButtonStyle.secondary, emoji='🔀', row=0)
|
||||
self.shuffle_button_on = ToggleShuffleButton(style=ButtonStyle.success, emoji='🔀', row=0)
|
||||
|
||||
self.play_pause_button = PlayPauseButton(style=ButtonStyle.primary, emoji='⏯', row=0)
|
||||
|
||||
self.next_button = NextTrackButton(style=ButtonStyle.primary, emoji='⏭', row=0)
|
||||
self.prev_button = PrevTrackButton(style=ButtonStyle.primary, emoji='⏮', row=0)
|
||||
|
||||
self.queue_button = Button(style=ButtonStyle.primary, emoji='📋', row=1)
|
||||
|
||||
self.add_item(self.repeat_button)
|
||||
if guild['repeat']:
|
||||
self.add_item(self.repeat_button_on)
|
||||
else:
|
||||
self.add_item(self.repeat_button_off)
|
||||
|
||||
self.add_item(self.prev_button)
|
||||
self.add_item(self.play_pause_button)
|
||||
self.add_item(self.next_button)
|
||||
self.add_item(self.shuffle_button)
|
||||
|
||||
if guild['shuffle']:
|
||||
self.add_item(self.shuffle_button_on)
|
||||
else:
|
||||
self.add_item(self.shuffle_button_off)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import aiohttp
|
||||
import asyncio
|
||||
from os import getenv
|
||||
from math import ceil
|
||||
from typing import cast
|
||||
from io import BytesIO
|
||||
@@ -39,7 +40,10 @@ async def generate_player_embed(track: Track) -> discord.Embed:
|
||||
color = await get_average_color_from_url(cover_url)
|
||||
|
||||
if explicit:
|
||||
title += ' <:explicit:1325879701117472869>'
|
||||
explicit_eid = getenv('EXPLICIT_EID')
|
||||
if not explicit_eid:
|
||||
raise ValueError('You must specify explicit emoji id in your enviroment.')
|
||||
title += ' <:explicit:' + explicit_eid + '>'
|
||||
|
||||
duration_m = duration // 60000
|
||||
duration_s = ceil(duration / 1000) - duration_m * 60
|
||||
@@ -99,10 +103,10 @@ async def get_average_color_from_url(url: str) -> int:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url) as response:
|
||||
response.raise_for_status()
|
||||
response = await response.read()
|
||||
result = await response.read()
|
||||
|
||||
img = Image.open(BytesIO(response))
|
||||
img = img.convert('RGB')
|
||||
img_file = Image.open(BytesIO(result))
|
||||
img = img_file.convert('RGB')
|
||||
width, height = img.size
|
||||
r_total, g_total, b_total = 0, 0, 0
|
||||
|
||||
@@ -157,7 +161,7 @@ class VoiceExtension:
|
||||
# If interaction from player buttons
|
||||
await ctx.edit(embed=embed)
|
||||
else:
|
||||
# If interaction from other buttons. They should have thair own response.
|
||||
# If interaction from other buttons. They should have their own response.
|
||||
await player.edit(embed=embed)
|
||||
|
||||
async def voice_check(self, ctx: ApplicationContext | Interaction) -> bool:
|
||||
@@ -174,7 +178,7 @@ class VoiceExtension:
|
||||
|
||||
token = self.users_db.get_ym_token(ctx.user.id)
|
||||
if not token:
|
||||
await ctx.respond('❌ Необходимо указать свой токен доступа с помощью комманды /login.', delete_after=15, ephemeral=True)
|
||||
await ctx.respond("❌ Необходимо указать свой токен доступа с помощью комманды /login.", delete_after=15, ephemeral=True)
|
||||
return False
|
||||
|
||||
channel = ctx.channel
|
||||
@@ -200,7 +204,7 @@ class VoiceExtension:
|
||||
ctx (ApplicationContext | Interaction): Command context.
|
||||
|
||||
Returns:
|
||||
discord.VoiceClient | None: Voice client.
|
||||
discord.VoiceClient | None: Voice client or None.
|
||||
"""
|
||||
|
||||
if isinstance(ctx, Interaction):
|
||||
@@ -211,8 +215,8 @@ class VoiceExtension:
|
||||
return cast(discord.VoiceClient, voice_chat)
|
||||
|
||||
async def play_track(self, ctx: ApplicationContext | Interaction, track: Track) -> str | None:
|
||||
"""Download ``track`` by its id and play it in the voice channel. Return track title on success and don't respond.
|
||||
If sound is already playing, add track id to the queue and respond.
|
||||
"""Download ``track`` by its id and play it in the voice channel. Return track title on success.
|
||||
If sound is already playing, add track id to the queue. There's no response to the context.
|
||||
|
||||
Args:
|
||||
ctx (ApplicationContext | Interaction): Context
|
||||
@@ -222,11 +226,11 @@ class VoiceExtension:
|
||||
str | None: Song title or None.
|
||||
"""
|
||||
if not ctx.guild:
|
||||
return
|
||||
return None
|
||||
|
||||
vc = self.get_voice_client(ctx)
|
||||
if not vc:
|
||||
return
|
||||
return None
|
||||
|
||||
if isinstance(ctx, Interaction):
|
||||
loop = ctx.client.loop
|
||||
@@ -253,11 +257,13 @@ class VoiceExtension:
|
||||
vc = self.get_voice_client(ctx)
|
||||
if vc:
|
||||
vc.pause()
|
||||
return
|
||||
|
||||
def resume_playing(self, ctx: ApplicationContext | Interaction) -> None:
|
||||
vc = self.get_voice_client(ctx)
|
||||
if vc:
|
||||
vc.resume()
|
||||
return
|
||||
|
||||
def stop_playing(self, ctx: ApplicationContext | Interaction) -> None:
|
||||
if not ctx.guild:
|
||||
@@ -267,10 +273,11 @@ class VoiceExtension:
|
||||
if vc:
|
||||
self.db.update(ctx.guild.id, {'current_track': None, 'is_stopped': True})
|
||||
vc.stop()
|
||||
return
|
||||
|
||||
async def next_track(self, ctx: ApplicationContext | Interaction) -> str | None:
|
||||
"""Switch to the next track in the queue. Return track title on success.
|
||||
Stop playing if tracks list is empty.
|
||||
Doesn't change track if stopped. Stop playing if tracks list is empty.
|
||||
|
||||
Args:
|
||||
ctx (ApplicationContext | Interaction): Context
|
||||
@@ -279,31 +286,36 @@ class VoiceExtension:
|
||||
str | None: Track title or None.
|
||||
"""
|
||||
if not ctx.guild or not ctx.user:
|
||||
return
|
||||
return None
|
||||
|
||||
gid = ctx.guild.id
|
||||
guild = self.db.get_guild(gid)
|
||||
token = self.users_db.get_ym_token(ctx.user.id)
|
||||
if guild.get('is_stopped'):
|
||||
return
|
||||
if guild['is_stopped']:
|
||||
return None
|
||||
|
||||
if not self.get_voice_client(ctx): # Silently return if bot got kicked
|
||||
return
|
||||
return None
|
||||
|
||||
current_track = guild['current_track']
|
||||
next_track = self.db.get_track(gid, 'next')
|
||||
if next_track and current_track:
|
||||
ym_track = None
|
||||
|
||||
if guild['repeat'] and current_track:
|
||||
return await self.repeat_current_track(ctx)
|
||||
elif guild['shuffle']:
|
||||
next_track = self.db.get_random_track(gid)
|
||||
else:
|
||||
next_track = self.db.get_track(gid, 'next')
|
||||
|
||||
if current_track:
|
||||
self.db.modify_track(gid, current_track, 'previous', 'insert')
|
||||
|
||||
if next_track:
|
||||
ym_track = Track.de_json(next_track, client=ClientAsync(token)) # type: ignore
|
||||
self.stop_playing(ctx)
|
||||
return await self.play_track(ctx, ym_track) # type: ignore
|
||||
elif next_track:
|
||||
ym_track = Track.de_json(next_track, client=ClientAsync(token)) # type: ignore
|
||||
self.stop_playing(ctx)
|
||||
return await self.play_track(ctx, ym_track) # type: ignore
|
||||
elif current_track:
|
||||
self.db.modify_track(gid, current_track, 'previous', 'insert')
|
||||
self.stop_playing(ctx)
|
||||
|
||||
return None
|
||||
|
||||
async def prev_track(self, ctx: ApplicationContext | Interaction) -> str | None:
|
||||
"""Switch to the previous track in the queue. Repeat curren the song if no previous tracks.
|
||||
@@ -317,21 +329,22 @@ class VoiceExtension:
|
||||
"""
|
||||
|
||||
if not ctx.guild or not ctx.user:
|
||||
return
|
||||
return None
|
||||
|
||||
gid = ctx.guild.id
|
||||
token = self.users_db.get_ym_token(ctx.user.id)
|
||||
current_track = self.db.get_track(gid, 'current')
|
||||
|
||||
prev_track = self.db.get_track(gid, 'previous')
|
||||
|
||||
title = None
|
||||
if prev_track:
|
||||
if current_track:
|
||||
self.db.modify_track(gid, current_track, 'next', 'insert')
|
||||
ym_track = Track.de_json(prev_track, client=ClientAsync(token)) # type: ignore
|
||||
self.stop_playing(ctx)
|
||||
return await self.play_track(ctx, ym_track) # type: ignore
|
||||
title = await self.play_track(ctx, ym_track) # type: ignore
|
||||
elif current_track:
|
||||
return await self.repeat_current_track(ctx)
|
||||
title = await self.repeat_current_track(ctx)
|
||||
|
||||
return title
|
||||
|
||||
async def repeat_current_track(self, ctx: ApplicationContext | Interaction) -> str | None:
|
||||
"""Repeat current track. Return track title on success.
|
||||
@@ -344,7 +357,7 @@ class VoiceExtension:
|
||||
"""
|
||||
|
||||
if not ctx.guild or not ctx.user:
|
||||
return
|
||||
return None
|
||||
|
||||
gid = ctx.guild.id
|
||||
token = self.users_db.get_ym_token(ctx.user.id)
|
||||
@@ -354,3 +367,5 @@ class VoiceExtension:
|
||||
ym_track = Track.de_json(current_track, client=ClientAsync(token)) # type: ignore
|
||||
self.stop_playing(ctx)
|
||||
return await self.play_track(ctx, ym_track) # type: ignore
|
||||
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user