impr: Minor code improvement.

This commit is contained in:
Lemon4ksan
2025-02-01 23:05:51 +03:00
parent a74bf152c0
commit 1449807184
3 changed files with 30 additions and 21 deletions

View File

@@ -273,7 +273,7 @@ class VoiceExtension:
await self.stop_playing(ctx) await self.stop_playing(ctx)
return await self.play_track(ctx, next_tracks[0], button_callback=button_callback) return await self.play_track(ctx, next_tracks[0], button_callback=button_callback)
async def voice_check(self, ctx: ApplicationContext | Interaction) -> bool: async def voice_check(self, ctx: ApplicationContext | Interaction, *, check_vibe_privilage: bool = True) -> bool:
"""Check if bot can perform voice tasks and respond if failed. """Check if bot can perform voice tasks and respond if failed.
Args: Args:
@@ -309,12 +309,13 @@ class VoiceExtension:
await ctx.respond("❌ Добавьте бота в голосовой канал при помощи команды /voice join.", delete_after=15, ephemeral=True) await ctx.respond("❌ Добавьте бота в голосовой канал при помощи команды /voice join.", delete_after=15, ephemeral=True)
return False return False
guild = self.db.get_guild(ctx.guild.id) if check_vibe_privilage:
member = cast(discord.Member, ctx.user) guild = self.db.get_guild(ctx.guild.id)
if guild['vibing'] and ctx.user.id != guild['current_viber_id'] and not member.guild_permissions.manage_channels: member = cast(discord.Member, ctx.user)
logging.debug("[VIBE] Context user is not the current viber") if guild['vibing'] and ctx.user.id != guild['current_viber_id'] and not member.guild_permissions.manage_channels:
await ctx.respond("❌ Вы не можете взаимодействовать с чужой волной!", delete_after=15, ephemeral=True) logging.debug("[VIBE] Context user is not the current viber")
return False await ctx.respond("❌ Вы не можете взаимодействовать с чужой волной!", delete_after=15, ephemeral=True)
return False
logging.debug("[VC_EXT] Voice requirements met") logging.debug("[VC_EXT] Voice requirements met")
return True return True

View File

@@ -52,7 +52,7 @@ class Voice(Cog, VoiceExtension):
if current_menu: if current_menu:
logging.info(f"[VOICE] Disabling current menu for guild {gid} due to multiple members") logging.info(f"[VOICE] Disabling current menu for guild {gid} due to multiple members")
self.db.update(gid, {'current_menu': None, 'repeat': False, 'shuffle': False}) self.db.update(gid, {'current_menu': None, 'repeat': False, 'shuffle': False, 'vibing': False})
try: try:
message = await channel.fetch_message(current_menu) message = await channel.fetch_message(current_menu)
await message.delete() await message.delete()
@@ -240,8 +240,9 @@ class Voice(Cog, VoiceExtension):
await ctx.respond("У вас нет прав для выполнения этой команды.", delete_after=15, ephemeral=True) await ctx.respond("У вас нет прав для выполнения этой команды.", delete_after=15, ephemeral=True)
return return
if await self.voice_check(ctx): if (vc := await self.get_voice_client(ctx)) and await self.voice_check(ctx):
await self.stop_playing(ctx, full=True) await self.stop_playing(ctx, full=True)
await vc.disconnect(force=True)
await ctx.respond("Отключение успешно!", delete_after=15, ephemeral=True) await ctx.respond("Отключение успешно!", delete_after=15, ephemeral=True)
logging.info(f"[VOICE] Successfully disconnected from voice channel in guild {ctx.guild.id}") logging.info(f"[VOICE] Successfully disconnected from voice channel in guild {ctx.guild.id}")

View File

@@ -58,7 +58,11 @@ class PlayPauseButton(Button, VoiceExtension):
if not vc or not interaction.message: if not vc or not interaction.message:
return return
embed = interaction.message.embeds[0] try:
embed = interaction.message.embeds[0]
except IndexError:
await interaction.respond("❌ Нет воспроизводимого трека.", delete_after=15, ephemeral=True)
return
if vc.is_paused(): if vc.is_paused():
vc.resume() vc.resume()
@@ -80,7 +84,7 @@ class NextTrackButton(Button, VoiceExtension):
return return
title = await self.next_track(interaction, button_callback=True) title = await self.next_track(interaction, button_callback=True)
if not title: if not title:
await interaction.respond(f"Нет треков в очереди.", delete_after=15, ephemeral=True) await interaction.respond(f"Нет треков в очереди.", delete_after=15, ephemeral=True)
class PrevTrackButton(Button, VoiceExtension): class PrevTrackButton(Button, VoiceExtension):
def __init__(self, **kwargs): def __init__(self, **kwargs):
@@ -102,7 +106,7 @@ class LikeButton(Button, VoiceExtension):
async def callback(self, interaction: Interaction) -> None: async def callback(self, interaction: Interaction) -> None:
logging.info('[MENU] Like button callback...') logging.info('[MENU] Like button callback...')
if not await self.voice_check(interaction): if not await self.voice_check(interaction, check_vibe_privilage=False):
return return
if not interaction.guild: if not interaction.guild:
@@ -148,7 +152,7 @@ class LyricsButton(Button, VoiceExtension):
async def callback(self, interaction: Interaction) -> None: async def callback(self, interaction: Interaction) -> None:
logging.info('[MENU] Lyrics button callback...') logging.info('[MENU] Lyrics button callback...')
if not await self.voice_check(interaction) or not interaction.guild_id or not interaction.user: if not await self.voice_check(interaction, check_vibe_privilage=False) or not interaction.guild_id or not interaction.user:
return return
ym_token = self.users_db.get_ym_token(interaction.user.id) ym_token = self.users_db.get_ym_token(interaction.user.id)
@@ -333,9 +337,9 @@ class AddToPlaylistSelect(Select, VoiceExtension):
self.ym_client = ym_client self.ym_client = ym_client
async def callback(self, interaction: Interaction): async def callback(self, interaction: Interaction):
if not interaction.data or not interaction.guild_id: if not await self.voice_check(interaction, check_vibe_privilage=False):
return return
if not interaction.data or 'values' not in interaction.data: if not interaction.guild_id or not interaction.data or 'values' not in interaction.data:
logging.warning('[MENU] No data in select callback') logging.warning('[MENU] No data in select callback')
return return
@@ -358,8 +362,6 @@ class AddToPlaylistSelect(Select, VoiceExtension):
except yandex_music.exceptions.NetworkError: except yandex_music.exceptions.NetworkError:
res = None res = None
# value=f"{playlist.kind or "-1"};{current_track['id']};{current_track['albums'][0]['id']};{playlist.revision};{playlist.uid}"
if res: if res:
await interaction.respond('✅ Добавлено в плейлист', delete_after=15, ephemeral=True) await interaction.respond('✅ Добавлено в плейлист', delete_after=15, ephemeral=True)
else: else:
@@ -371,7 +373,7 @@ class AddToPlaylistButton(Button, VoiceExtension):
VoiceExtension.__init__(self, None) VoiceExtension.__init__(self, None)
async def callback(self, interaction: Interaction): async def callback(self, interaction: Interaction):
if not await self.voice_check(interaction) or not interaction.guild_id: if not await self.voice_check(interaction, check_vibe_privilage=False) or not interaction.guild_id:
return return
client = await self.init_ym_client(interaction) client = await self.init_ym_client(interaction)
@@ -433,12 +435,17 @@ class MenuView(View, VoiceExtension):
self.add_item(self.next_button) self.add_item(self.next_button)
self.add_item(self.shuffle_button) self.add_item(self.shuffle_button)
if isinstance(self.ctx, RawReactionActionEvent) or len(cast(VoiceChannel, self.ctx.channel).members) > 2: if not isinstance(self.ctx, RawReactionActionEvent) and len(cast(VoiceChannel, self.ctx.channel).members) > 2:
self.like_button.disabled = True self.dislike_button.disabled = True
elif likes and current_track and str(current_track['id']) in [str(like.id) for like in likes]: elif likes and current_track and str(current_track['id']) in [str(like.id) for like in likes]:
self.like_button.style = ButtonStyle.success self.like_button.style = ButtonStyle.success
if not current_track or not current_track['lyrics_available']: if not current_track:
self.lyrics_button.disabled = True
self.like_button.disabled = True
self.dislike_button.disabled = True
self.add_to_playlist_button.disabled = True
elif not current_track['lyrics_available']:
self.lyrics_button.disabled = True self.lyrics_button.disabled = True
self.add_item(self.like_button) self.add_item(self.like_button)