up-to-date actual

This commit is contained in:
2025-03-20 18:47:51 +03:00
parent 76c7bcf2c6
commit 74d886bf0e
12 changed files with 473 additions and 419 deletions

View File

@@ -8,7 +8,7 @@ import yandex_music.exceptions
from yandex_music import Track, TrackShort, ClientAsync as YMClient
import discord
from discord import Interaction, ApplicationContext, RawReactionActionEvent, VoiceChannel
from discord import Interaction, ApplicationContext, RawReactionActionEvent
from MusicBot.cogs.utils.base_bot import BaseBot
from MusicBot.cogs.utils import generate_item_embed
@@ -63,12 +63,10 @@ class VoiceExtension(BaseBot):
if guild['current_menu']:
logging.info(f"[VC_EXT] Deleting old menu message {guild['current_menu']} in guild {ctx.guild_id}")
if (message := await self.get_menu_message(ctx, guild['current_menu'])):
await message.delete()
await self._delete_menu_message(ctx, guild['current_menu'], ctx.guild_id)
await self.update_menu_views_dict(ctx, disable=disable)
interaction = await self.send_response_message(ctx, embed=embed, view=self.menu_views[ctx.guild_id])
await self.init_menu_view(ctx, ctx.guild_id, disable=disable)
interaction = await self.respond(ctx, embed=embed, view=self.menu_views[ctx.guild_id])
response = await interaction.original_response() if isinstance(interaction, discord.Interaction) else interaction
if response:
@@ -120,7 +118,6 @@ class VoiceExtension(BaseBot):
Args:
ctx (ApplicationContext | Interaction | RawReactionActionEvent): Context.
menu_mid (int): Id of the menu message to update. Defaults to None.
menu_message (discord.Message | None): Message to update. If None, fetches menu from channel using `menu_mid`. Defaults to None.
button_callback (bool, optional): Should be True if the function is being called from button callback. Defaults to False.
@@ -174,7 +171,7 @@ class VoiceExtension(BaseBot):
else:
embed.remove_footer()
await self.update_menu_views_dict(ctx)
await self.menu_views[ctx.guild_id].update()
try:
if isinstance(ctx, Interaction) and button_callback:
# If interaction from menu buttons
@@ -193,7 +190,6 @@ class VoiceExtension(BaseBot):
self,
ctx: ApplicationContext | Interaction | RawReactionActionEvent,
*,
menu_message: discord.Message | None = None,
button_callback: bool = False,
disable: bool = False
) -> bool:
@@ -201,8 +197,6 @@ class VoiceExtension(BaseBot):
Args:
ctx (ApplicationContext | Interaction | RawReactionActionEvent): Context.
guild (ExplicitGuild): Guild data.
menu_message (discord.Message | None, optional): Menu message to update. Defaults to None.
button_callback (bool, optional): If True, the interaction is from a button callback. Defaults to False.
disable (bool, optional): Disable the view if True. Defaults to False.
@@ -210,29 +204,33 @@ class VoiceExtension(BaseBot):
bool: True if the view was updated, False otherwise.
"""
logging.debug("[VC_EXT] Updating menu view")
if not ctx.guild_id:
logging.warning("[VC_EXT] Guild ID not found in context inside 'update_menu_view'")
logging.warning("[VC_EXT] Guild ID not found in context")
return False
if not menu_message:
guild = await self.db.get_guild(ctx.guild_id, projection={'current_menu': 1})
if not guild['current_menu']:
return False
guild = await self.db.get_guild(ctx.guild_id, projection={'current_menu': 1})
menu_message = await self.get_menu_message(ctx, guild['current_menu']) if not menu_message else menu_message
if not menu_message:
if not guild['current_menu']:
logging.warning("[VC_EXT] Current menu not found in guild data")
return False
await self.update_menu_views_dict(ctx, disable=disable)
if ctx.guild_id not in self.menu_views:
logging.debug("[VC_EXT] Creating new menu view")
await self.init_menu_view(ctx, ctx.guild_id, disable=disable)
view = self.menu_views[ctx.guild_id]
await view.update(disable=disable)
try:
if isinstance(ctx, Interaction) and button_callback:
# If interaction from menu buttons
await ctx.edit(view=self.menu_views[ctx.guild_id])
await ctx.edit(view=view)
else:
# If interaction from other buttons or commands. They should have their own response.
await menu_message.edit(view=self.menu_views[ctx.guild_id])
if (menu_message := await self.get_menu_message(ctx, guild['current_menu'])):
await menu_message.edit(view=view)
except discord.DiscordException as e:
logging.warning(f"[VC_EXT] Error while updating menu view: {e}")
return False
@@ -338,40 +336,40 @@ class VoiceExtension(BaseBot):
"""
if not ctx.user:
logging.info("[VC_EXT] User not found in context inside 'voice_check'")
await ctx.respond("Пользователь не найден.", delete_after=15, ephemeral=True)
await self.respond(ctx, "error", "Пользователь не найден.", delete_after=15, ephemeral=True)
return False
if not ctx.guild_id:
logging.info("[VC_EXT] Guild id not found in context inside 'voice_check'")
await ctx.respond("Эта команда может быть использована только на сервере.", delete_after=15, ephemeral=True)
await self.respond(ctx, "error", "Эта команда может быть использована только на сервере.", delete_after=15, ephemeral=True)
return False
if not await self.get_ym_token(ctx):
logging.debug(f"[VC_EXT] No token found for user {ctx.user.id}")
await ctx.respond("Укажите токен через /account login.", delete_after=15, ephemeral=True)
await self.respond(ctx, "error", "Укажите токен через /account login.", delete_after=15, ephemeral=True)
return False
if not isinstance(ctx.channel, discord.VoiceChannel):
logging.debug("[VC_EXT] User is not in a voice channel")
await ctx.respond("Вы должны отправить команду в чате голосового канала.", delete_after=15, ephemeral=True)
await self.respond(ctx, "error", "Вы должны отправить команду в чате голосового канала.", delete_after=15, ephemeral=True)
return False
if ctx.user.id not in ctx.channel.voice_states:
logging.debug("[VC_EXT] User is not connected to the voice channel")
await ctx.respond("Вы должны находиться в голосовом канале.", delete_after=15, ephemeral=True)
await self.respond(ctx, "error", "Вы должны находиться в голосовом канале.", delete_after=15, ephemeral=True)
return False
voice_clients = ctx.client.voice_clients if isinstance(ctx, Interaction) else ctx.bot.voice_clients
if not discord.utils.get(voice_clients, guild=ctx.guild):
logging.debug("[VC_EXT] Voice client not found")
await ctx.respond("Добавьте бота в голосовой канал при помощи команды /voice join.", delete_after=15, ephemeral=True)
await self.respond(ctx, "error", "Добавьте бота в голосовой канал при помощи команды /voice join.", delete_after=15, ephemeral=True)
return False
if check_vibe_privilage:
guild = await self.db.get_guild(ctx.guild_id, projection={'current_viber_id': 1, 'vibing': 1})
if guild['vibing'] and ctx.user.id != guild['current_viber_id']:
logging.debug("[VIBE] Context user is not the current viber")
await ctx.respond("Вы не можете изменять чужую волну!", delete_after=15, ephemeral=True)
await self.respond(ctx, "error", "Вы не можете изменять чужую волну!", delete_after=15, ephemeral=True)
return False
logging.debug("[VC_EXT] Voice requirements met")
@@ -411,7 +409,6 @@ class VoiceExtension(BaseBot):
track: Track | dict[str, Any],
*,
vc: discord.VoiceClient | None = None,
menu_message: discord.Message | None = None,
button_callback: bool = False,
) -> str | None:
"""Play `track` in the voice channel. Avoids additional vibe feedback used in `next_track` and `previous_track`.
@@ -421,7 +418,6 @@ class VoiceExtension(BaseBot):
ctx (ApplicationContext | Interaction | RawReactionActionEvent): Context.
track (dict[str, Any]): Track to play.
vc (discord.VoiceClient | None, optional): Voice client. Defaults to None.
menu_message (discord.Message | None, optional): Menu message to update. Defaults to None.
button_callback (bool, optional): Should be True if the function is being called from button callback. Defaults to False.
Returns:
@@ -444,7 +440,6 @@ class VoiceExtension(BaseBot):
ctx,
track,
vc=vc,
menu_message=menu_message,
button_callback=button_callback
)
@@ -501,7 +496,6 @@ class VoiceExtension(BaseBot):
vc: discord.VoiceClient | None = None,
*,
after: bool = False,
menu_message: discord.Message | None = None,
button_callback: bool = False
) -> str | None:
"""Switch to the next track in the queue. Return track title on success.
@@ -524,9 +518,12 @@ class VoiceExtension(BaseBot):
logging.warning("[VC_EXT] Guild ID or User ID not found in context inside 'next_track'")
return None
guild = await self.db.get_guild(ctx.guild_id, projection={'shuffle': 1, 'repeat': 1, 'is_stopped': 1, 'current_menu': 1, 'vibing': 1, 'current_track': 1})
guild = await self.db.get_guild(ctx.guild_id, projection={
'shuffle': 1, 'repeat': 1, 'is_stopped': 1,
'current_menu': 1, 'vibing': 1, 'current_track': 1
})
if guild['is_stopped'] and after:
if after and guild['is_stopped']:
logging.debug("[VC_EXT] Playback is stopped, skipping after callback.")
return None
@@ -534,8 +531,9 @@ class VoiceExtension(BaseBot):
logging.debug("[VC_EXT] Adding current track to history")
await self.db.modify_track(ctx.guild_id, guild['current_track'], 'previous', 'insert')
if after and not await self.update_menu_view(ctx, menu_message=menu_message, disable=True):
await self.send_response_message(ctx, "Не удалось обновить меню.", ephemeral=True, delete_after=15)
if after and guild['current_menu']:
if not await self.update_menu_view(ctx, button_callback=button_callback, disable=True):
await self.respond(ctx, "error", "Не удалось обновить меню.", ephemeral=True, delete_after=15)
if guild['vibing'] and guild['current_track']:
await self.send_vibe_feedback(ctx, 'trackFinished' if after else 'skip', guild['current_track'])
@@ -570,10 +568,17 @@ class VoiceExtension(BaseBot):
logging.info("[VC_EXT] No next track found")
if after:
await self.db.update(ctx.guild_id, {'is_stopped': True, 'current_track': None})
if guild['current_menu']:
await self.update_menu_view(ctx, button_callback=button_callback)
return None
async def play_previous_track(self, ctx: ApplicationContext | Interaction | RawReactionActionEvent, button_callback: bool = False) -> str | None:
async def play_previous_track(
self,
ctx: ApplicationContext | Interaction | RawReactionActionEvent,
button_callback: bool = False
) -> str | None:
"""Switch to the previous track in the queue. Repeat current track if no previous one found.
Return track title on success. Should be called only if there's already track playing.
@@ -643,55 +648,12 @@ class VoiceExtension(BaseBot):
return []
return collection.tracks
async def react_track(
self,
ctx: ApplicationContext | Interaction,
action: Literal['like', 'dislike']
) -> tuple[bool, Literal['added', 'removed'] | None]:
"""Like or dislike current track. Return track title on success.
Args:
ctx (ApplicationContext | Interaction): Context.
action (Literal['like', 'dislike']): Action to perform.
Returns:
(tuple[bool, Literal['added', 'removed'] | None]): Tuple with success status and action.
"""
if not (gid := ctx.guild_id) or not ctx.user:
logging.warning("[VC_EXT] Guild or User not found")
return (False, None)
if not (current_track := await self.db.get_track(gid, 'current')):
logging.debug("[VC_EXT] Current track not found")
return (False, None)
if not (client := await self.init_ym_client(ctx)):
return (False, None)
if action == 'like':
tracks = await client.users_likes_tracks()
add_func = client.users_likes_tracks_add
remove_func = client.users_likes_tracks_remove
else:
tracks = await client.users_dislikes_tracks()
add_func = client.users_dislikes_tracks_add
remove_func = client.users_dislikes_tracks_remove
if tracks is None:
logging.debug(f"[VC_EXT] No {action}s found")
return (False, None)
if str(current_track['id']) not in [str(track.id) for track in tracks]:
logging.debug(f"[VC_EXT] Track not found in {action}s. Adding...")
await add_func(current_track['id'])
return (True, 'added')
else:
logging.debug(f"[VC_EXT] Track found in {action}s. Removing...")
await remove_func(current_track['id'])
return (True, 'removed')
async def proccess_vote(self, ctx: RawReactionActionEvent, guild: ExplicitGuild, channel: VoiceChannel, vote_data: MessageVotes) -> bool:
async def proccess_vote(
self,
ctx: RawReactionActionEvent,
guild: ExplicitGuild,
vote_data: MessageVotes) -> bool:
"""Proccess vote and perform action from `vote_data` and respond. Return True on success.
Args:
@@ -710,16 +672,16 @@ class VoiceExtension(BaseBot):
return False
if not guild['current_menu'] and not await self.send_menu_message(ctx):
await channel.send(content=f"Не удалось отправить меню! Попробуйте ещё раз.", delete_after=15)
await self.respond(ctx, "error", "Не удалось отправить меню! Попробуйте ещё раз.", delete_after=15)
return False
if vote_data['action'] in ('next', 'previous'):
if not guild.get(f'{vote_data['action']}_tracks'):
logging.info(f"[VOICE] No {vote_data['action']} tracks found for message {ctx.message_id}")
await channel.send(content=f"Очередь пуста!", delete_after=15)
await self.respond(ctx, "error", "Очередь пуста!", delete_after=15)
elif not (await self.play_next_track(ctx) if vote_data['action'] == 'next' else await self.play_previous_track(ctx)):
await channel.send(content=f"Ошибка при смене трека! Попробуйте ещё раз.", delete_after=15)
await self.respond(ctx, "error", "Ошибка при смене трека! Попробуйте ещё раз.", delete_after=15)
return False
elif vote_data['action'] == 'add_track':
@@ -730,9 +692,9 @@ class VoiceExtension(BaseBot):
await self.db.modify_track(guild['_id'], vote_data['vote_content'], 'next', 'append')
if guild['current_track']:
await channel.send(content=f"Трек был добавлен в очередь!", delete_after=15)
await self.respond(ctx, "success", "Трек был добавлен в очередь!", delete_after=15)
elif not await self.play_next_track(ctx):
await channel.send(content=f"Ошибка при воспроизведении! Попробуйте ещё раз.", delete_after=15)
await self.respond(ctx, "error", "Ошибка при воспроизведении! Попробуйте ещё раз.", delete_after=15)
return False
elif vote_data['action'] in ('add_album', 'add_artist', 'add_playlist'):
@@ -744,14 +706,14 @@ class VoiceExtension(BaseBot):
await self.db.modify_track(guild['_id'], vote_data['vote_content'], 'next', 'extend')
if guild['current_track']:
await channel.send(content=f"Контент был добавлен в очередь!", delete_after=15)
await self.respond(ctx, "success", "Контент был добавлен в очередь!", delete_after=15)
elif not await self.play_next_track(ctx):
await channel.send(content=f"Ошибка при воспроизведении! Попробуйте ещё раз.", delete_after=15)
await self.respond(ctx, "error", "Ошибка при воспроизведении! Попробуйте ещё раз.", delete_after=15)
return False
elif vote_data['action'] == 'play/pause':
if not (vc := await self.get_voice_client(ctx)):
await channel.send(content=f"Ошибка при изменении воспроизведения! Попробуйте ещё раз.", delete_after=15)
await self.respond(ctx, "error", "Ошибка при изменении воспроизведения! Попробуйте ещё раз.", delete_after=15)
return False
if vc.is_playing():
@@ -767,31 +729,31 @@ class VoiceExtension(BaseBot):
elif vote_data['action'] == 'clear_queue':
await self.db.update(ctx.guild_id, {'previous_tracks': [], 'next_tracks': []})
await channel.send("Очередь и история сброшены.", delete_after=15)
await self.respond(ctx, "success", "Очередь и история сброшены.", delete_after=15)
elif vote_data['action'] == 'stop':
if await self.stop_playing(ctx, full=True):
await channel.send("Воспроизведение остановлено.", delete_after=15)
await self.respond(ctx, "success", "Воспроизведение остановлено.", delete_after=15)
else:
await channel.send("Произошла ошибка при остановке воспроизведения.", delete_after=15)
await self.respond(ctx, "error", "Произошла ошибка при остановке воспроизведения.", delete_after=15)
return False
elif vote_data['action'] == 'vibe_station':
vibe_type, vibe_id, viber_id = vote_data['vote_content'] if isinstance(vote_data['vote_content'], list) else (None, None, None)
if not vibe_type or not vibe_id or not viber_id:
logging.warning(f"[VOICE] Recieved empty vote context for message {ctx.message_id}")
await channel.send("Произошла ошибка при обновлении станции.", delete_after=15)
await self.respond(ctx, "error", "Произошла ошибка при обновлении станции.", delete_after=15)
return False
if not await self.update_vibe(ctx, vibe_type, vibe_id, viber_id=viber_id):
await channel.send("Операция не удалась. Возможно, у вес нет подписки на Яндекс Музыку.", delete_after=15)
await self.respond(ctx, "error", "Операция не удалась. Возможно, у вес нет подписки на Яндекс Музыку.", delete_after=15)
return False
if (next_track := await self.db.get_track(ctx.guild_id, 'next')):
await self.play_track(ctx, next_track)
else:
await channel.send("Не удалось воспроизвести трек.", delete_after=15)
await self.respond(ctx, "error", "Не удалось воспроизвести трек.", delete_after=15)
return False
else:
@@ -825,8 +787,6 @@ class VoiceExtension(BaseBot):
user = await self.users_db.get_user(uid, projection={'vibe_batch_id': 1, 'vibe_type': 1, 'vibe_id': 1})
if not (client := await self.init_ym_client(ctx)):
logging.info(f"[VC_EXT] Failed to init YM client for user {user['_id']}")
await self.send_response_message(ctx, "❌ Что-то пошло не так. Попробуйте позже.", delete_after=15, ephemeral=True)
return False
if feedback_type not in ('radioStarted', 'trackStarted') and track['duration_ms']:
@@ -895,7 +855,6 @@ class VoiceExtension(BaseBot):
track: Track,
*,
vc: discord.VoiceClient | None = None,
menu_message: discord.Message | None = None,
button_callback: bool = False,
retry: bool = False
) -> str | None:
@@ -906,7 +865,6 @@ class VoiceExtension(BaseBot):
ctx (ApplicationContext | Interaction | RawReactionActionEvent): Context.
track (Track): Track to play.
vc (discord.VoiceClient | None): Voice client.
menu_message (discord.Message | None): Menu message. If None, fetches menu from channel using message id from database. Defaults to None.
button_callback (bool): Should be True if the function is being called from button callback. Defaults to False.
retry (bool): Whether the function is called again.
@@ -928,21 +886,25 @@ class VoiceExtension(BaseBot):
await self._download_track(ctx.guild_id, track)
except yandex_music.exceptions.TimedOutError:
if not retry:
return await self._play_track(ctx, track, vc=vc, menu_message=menu_message, button_callback=button_callback, retry=True)
return await self._play_track(ctx, track, vc=vc, button_callback=button_callback, retry=True)
await self.send_response_message(ctx, f"😔 Не удалось загрузить трек. Попробуйте сбросить меню.", delete_after=15)
await self.respond(ctx, "error", "Не удалось загрузить трек. Попробуйте сбросить меню.", delete_after=15)
logging.error(f"[VC_EXT] Failed to download track '{track.title}'")
return None
except yandex_music.exceptions.InvalidBitrateError:
logging.error(f"[VC_EXT] Invalid bitrate while playing track '{track.title}'")
await self.respond(ctx, "error", "У трека отсутствует необходимый битрейт. Его проигрывание невозможно.", delete_after=15, ephemeral=True)
return None
async with aiofiles.open(f'music/{ctx.guild_id}.mp3', "rb") as f:
track_bytes = io.BytesIO(await f.read())
song = discord.FFmpegPCMAudio(track_bytes, pipe=True, options='-vn -b:a 64k -filter:a "volume=0.15"')
await self.db.set_current_track(ctx.guild_id, track)
if menu_message or guild['current_menu']:
# Updating menu message before playing to prevent delay and avoid FFMPEG lags.
await self.update_menu_embed_and_view(ctx, menu_message=menu_message, button_callback=button_callback)
if guild['current_menu']:
await self.update_menu_embed_and_view(ctx, button_callback=button_callback)
if not guild['vibing']:
# Giving FFMPEG enough time to process the audio file
@@ -953,11 +915,7 @@ class VoiceExtension(BaseBot):
vc.play(song, after=lambda exc: asyncio.run_coroutine_threadsafe(self.play_next_track(ctx, after=True), loop))
except discord.errors.ClientException as e:
logging.error(f"[VC_EXT] Error while playing track '{track.title}': {e}")
await self.send_response_message(ctx, f"Не удалось проиграть трек. Попробуйте сбросить меню.", delete_after=15, ephemeral=True)
return None
except yandex_music.exceptions.InvalidBitrateError:
logging.error(f"[VC_EXT] Invalid bitrate while playing track '{track.title}'")
await self.send_response_message(ctx, f"У трека отсутствует необходимый битрейт. Его проигрывание невозможно.", delete_after=15, ephemeral=True)
await self.respond(ctx, "error", "Не удалось проиграть трек. Попробуйте сбросить меню.", delete_after=15, ephemeral=True)
return None
logging.info(f"[VC_EXT] Playing track '{track.title}'")