Skip to content

Commit

Permalink
Merge pull request #8 from ChocoMeow/beta
Browse files Browse the repository at this point in the history
Vocard v2.6.4 Update: Improved Dashboard Functionality and Performance
  • Loading branch information
ChocoMeow authored Jun 3, 2023
2 parents ac37530 + 06e7e5b commit 7809afe
Show file tree
Hide file tree
Showing 30 changed files with 1,232 additions and 269 deletions.
9 changes: 4 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
Demo:
[Discord Bot Demo](https://discord.com/api/oauth2/authorize?client_id=890399639008866355&permissions=36708608&scope=bot%20applications.commands),
[Dashboard Demo](http://vocard.xyz)
[Dashboard Demo](https://vocard.xyz)

## Tutorial
Click on the image below to watch the tutorial on Youtube.
Expand All @@ -22,15 +22,14 @@ Click on the image below to watch the tutorial on Youtube.
<img src="https://user-images.githubusercontent.com/94597336/227766416-22ae3d91-40d9-44c0-bde1-9d40bd54c3af.png">

### Dashboard
<img src="https://user-images.githubusercontent.com/94597336/227766460-2c8e7718-c1c2-4c8a-8c0e-185d81db20cc.png">
<img src="https://user-images.githubusercontent.com/94597336/227766493-e7010813-077b-486a-b45c-4fbdc86f40bc.png">

<img src="https://github.com/ChocoMeow/Vocard/assets/94597336/53f31f9f-57c5-452c-8317-114125ddbf03">
<img src="https://github.com/ChocoMeow/Vocard/assets/94597336/b2acd87a-e910-4247-8d5a-418f3782f63f">

## Run the Projects
[![Run on Repl.it](https://replit.com/badge/github/ChocoMeow/Vocard)](https://replit.com/new/github/ChocoMeow/Vocard)

## Requirements
* [Python 3.8+](https://www.python.org/downloads/)
* [Python 3.10+](https://www.python.org/downloads/)
* [Modules in requirements](https://github.com/ChocoMeow/Vocard/blob/main/requirements.txt)
* [Lavalink Server (Requires 3.7.0+)](https://github.com/freyacodes/Lavalink)

Expand Down
1 change: 0 additions & 1 deletion cogs/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -779,6 +779,5 @@ async def ping(self, ctx: commands.Context):

await ctx.send(embed=embed)


async def setup(bot: commands.Bot) -> None:
await bot.add_cog(Basic(bot))
4 changes: 2 additions & 2 deletions cogs/listeners.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ async def start_nodes(self) -> None:
spotify_client_id=func.tokens.spotify_client_id,
spotify_client_secret=func.tokens.spotify_client_secret,
**n)
except:
print(f'Node {n["identifier"]} is not able to connect!')
except Exception as e:
print(f'Node {n["identifier"]} is not able to connect! - Reason: {e}')

@commands.Cog.listener()
async def on_voicelink_track_end(self, player: voicelink.Player, track, _):
Expand Down
62 changes: 28 additions & 34 deletions cogs/playlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

from discord import app_commands
from discord.ext import commands
from tldextract import extract
from function import (
time as ctime,
get_playlist,
Expand Down Expand Up @@ -120,9 +119,8 @@ async def play(self, ctx: commands.Context, name: str = None, value: int = None)

playtrack = []
for track in result['playlist']['tracks'][:max_t]:
track['info']['length'] *= 1000
playtrack.append(voicelink.Track(track_id=track['id'], info=track['info'], requester=ctx.author, spotify=True if extract(
track['info']['uri']).domain == 'spotify' else False))
playtrack.append(voicelink.Track(track_id=track, info=voicelink.decode(track), requester=ctx.author))

tracks = {"name": result['playlist']['name'], "tracks": playtrack}

if not tracks:
Expand Down Expand Up @@ -152,8 +150,7 @@ async def view(self, ctx: commands.Context) -> None:
try:
if playlist['type'] == 'link':
tracks = await search_playlist(playlist['uri'], requester=ctx.author)
results.append({'emoji': ('🔒' if max_p < index else '🔗'), 'id': data, 'time': tracks['time'], 'name': playlist[
'name'], 'tracks': tracks['tracks'], 'perms': playlist['perms'], 'type': playlist['type']})
results.append({'emoji': ('🔒' if max_p < index else '🔗'), 'id': data, 'time': tracks['time'], 'name': playlist['name'], 'tracks': tracks['tracks'], 'perms': playlist['perms'], 'type': playlist['type']})
else:
if share := playlist['type'] == 'share':
playlist = await check_playlist_perms(ctx.author.id, playlist['user'], playlist['referId'])
Expand All @@ -162,25 +159,25 @@ async def view(self, ctx: commands.Context) -> None:
continue
if playlist['type'] == 'link':
tracks = await search_playlist(playlist['uri'], requester=ctx.author)
results.append({'emoji': ('🔒' if max_p < index else '🤝'), 'id': data, 'time': tracks['time'], 'name': user[data][
'name'], 'tracks': tracks['tracks'], 'perms': playlist['perms'], 'owner': user[data]['user'], 'type': 'share'})
results.append({'emoji': ('🔒' if max_p < index else '🤝'), 'id': data, 'time': tracks['time'], 'name': user[data]['name'], 'tracks': tracks['tracks'], 'perms': playlist['perms'], 'owner': user[data]['user'], 'type': 'share'})
continue
init = []
for track in playlist['tracks']:
time += track['info']['length'] * 1000
results.append({'emoji': ('🔒' if max_p < index else ('🤝' if share else '❤️')), 'id': data, 'time': ctime(
time), 'name': user[data]['name'], 'tracks': playlist['tracks'], 'perms': playlist['perms'], 'owner': user[data].get('user', None), 'type': user[data]['type']})
except:
results.append({'emoji': '⛔', 'id': data, 'time': '00:00',
'name': 'Error', 'tracks': [], 'type': 'error'})
dt = voicelink.decode(track)
time += dt.get("length", 0)
init.append(dt)
playlist['tracks'] = init
results.append({'emoji': ('🔒' if max_p < index else ('🤝' if share else '❤️')), 'id': data, 'time': ctime(time), 'name': user[data]['name'], 'tracks': playlist['tracks'], 'perms': playlist['perms'], 'owner': user[data].get('user', None), 'type': user[data]['type']})

except Exception as e:
results.append({'emoji': '⛔', 'id': data, 'time': '00:00', 'name': 'Error', 'tracks': [], 'type': 'error'})

embed = discord.Embed(title=get_lang(ctx.guild.id, 'playlistViewTitle').format(ctx.author.name),
description='```%0s %4s %10s %10s %10s\n' % tuple(get_lang(ctx.guild.id, 'playlistViewHeaders')) + '\n'.join(
'%0s %3s. %10s %10s %10s' % (info['emoji'], info['id'], f"[{info['time']}]", info['name'], len(info['tracks'])) for info in results) + '```',
description='```%0s %4s %10s %10s %10s\n' % tuple(get_lang(ctx.guild.id, 'playlistViewHeaders')) + '\n'.join('%0s %3s. %10s %10s %10s' % (info['emoji'], info['id'], f"[{info['time']}]", info['name'], len(info['tracks'])) for info in results) + '```',
color=settings.embed_color)
embed.add_field(name=get_lang(ctx.guild.id, 'playlistMaxP'),
value=f"➥ {len(user)}/{max_p}", inline=True)
embed.add_field(name=get_lang(ctx.guild.id,
'playlistMaxT'), value=f"➥ {max_t}", inline=True)

embed.add_field(name=get_lang(ctx.guild.id, 'playlistMaxP'), value=f"➥ {len(user)}/{max_p}", inline=True)
embed.add_field(name=get_lang(ctx.guild.id, 'playlistMaxT'), value=f"➥ {max_t}", inline=True)
embed.set_footer(text=get_lang(ctx.guild.id, 'playlistFooter'))

view = PlaylistView(embed, results, ctx.author)
Expand All @@ -197,27 +194,25 @@ async def create(self, ctx: commands.Context, name: str, link: str = None):
"Create your custom playlist."
if len(name) > 10:
return await ctx.send(get_lang(ctx.guild.id, 'playlistOverText'), ephemeral=True)
isLinkType = True if link else False

rank, max_p, max_t = await checkroles(ctx.author.id)
if isLinkType and rank != "Gold":
return await ctx.send(get_lang(ctx.guild.id, 'playlistCreateError'), ephemeral=True)
user = await check_playlist(ctx, full=True)
if not user:
return await create_account(ctx)

if len(user) >= max_p:
return await ctx.send(get_lang(ctx.guild.id, 'overPlaylistCreation').format(max_p), ephemeral=True)

for data in user:
if user[data]['name'].lower() == name.lower():
return await ctx.send(get_lang(ctx.guild.id, 'playlistExists'), ephemeral=True)
if isLinkType:
if link:
tracks = await voicelink.NodePool.get_node().get_tracks(link, requester=ctx.author)
if not isinstance(tracks, voicelink.Playlist):
return await ctx.send(get_lang(ctx.guild.id, 'playlistNotInvaildUrl'), ephemeral=True)

playlist_name.pop(str(ctx.author.id), None)
data = {'uri': link, 'perms': {'read': []}, 'name': name, 'type': 'link'} if isLinkType else {
'tracks': [], 'perms': {'read': [], 'write': [], 'remove': []}, 'name': name, 'type': 'playlist'}
data = {'uri': link, 'perms': {'read': []}, 'name': name, 'type': 'link'} if link else {'tracks': [], 'perms': {'read': [], 'write': [], 'remove': []}, 'name': name, 'type': 'playlist'}
await update_playlist(ctx.author.id, {f"playlist.{assign_playlistId([data for data in user])}": data})
await ctx.send(get_lang(ctx.guild.id, 'playlistCreated').format(name))

Expand Down Expand Up @@ -353,24 +348,22 @@ async def add(self, ctx: commands.Context, name: str, query: str) -> None:
return await ctx.send(get_lang(ctx.guild.id, 'playlistNotFound').format(name), ephemeral=True)
if result['playlist']['type'] in ['share', 'link']:
return await ctx.send(get_lang(ctx.guild.id, 'playlistNotAllow'), ephemeral=True)

rank, max_p, max_t = await checkroles(ctx.author.id)

if len(result['playlist']['tracks']) >= max_t:
return await ctx.send(get_lang(ctx.guild.id, 'playlistLimitTrack').format(max_t), ephemeral=True)

results = await voicelink.NodePool.get_node().get_tracks(query, requester=ctx.author)
if not results:
return await ctx.send(get_lang(ctx.guild.id, 'noTrackFound'))

if isinstance(results, voicelink.Playlist):
return await ctx.send(get_lang(ctx.guild.id, 'playlistPlaylistLink'), ephemeral=True)

if results[0].is_stream:
return await ctx.send(get_lang(ctx.guild.id, 'playlistStream'), ephemeral=True)

await update_playlist(ctx.author.id, {f'playlist.{result["id"]}.tracks': {'id': results[0].track_id, 'info': {'identifier': results[0].identifier,
'author': results[0].author,
'length': results[0].length / 1000,
'title': results[0].title,
'uri': results[0].uri}}}, push=True)
await update_playlist(ctx.author.id, {f'playlist.{result["id"]}.tracks': results[0].track_id}, push=True)
await ctx.send(get_lang(ctx.guild.id, 'playlistAdded').format(results[0].title, ctx.author, result['playlist']['name']))

@playlist.command(name="remove", aliases=get_aliases("remove"))
Expand All @@ -393,7 +386,9 @@ async def remove(self, ctx: commands.Context, name: str, position: int):
return await ctx.send(get_lang(ctx.guild.id, 'playlistPositionNotFound').format(position, name))

await update_playlist(ctx.author.id, {f'playlist.{result["id"]}.tracks': result['playlist']['tracks'][position - 1]}, pull=True, mode=False)
await ctx.send(get_lang(ctx.guild.id, 'playlistRemoved').format(result['playlist']['tracks'][position - 1]['info']['title'], ctx.author, name))

track = voicelink.decode(result['playlist']['tracks'][position - 1])
await ctx.send(get_lang(ctx.guild.id, 'playlistRemoved').format(track.get("title"), ctx.author, name))

@playlist.command(name="clear", aliases=get_aliases("clear"))
@commands.dynamic_cooldown(cooldown_check, commands.BucketType.guild)
Expand All @@ -412,6 +407,5 @@ async def clear(self, ctx: commands.Context, name: str) -> None:
await update_playlist(ctx.author.id, {f'playlist.{result["id"]}.tracks': []})
await ctx.send(get_lang(ctx.guild.id, 'playlistClear').format(name))


async def setup(bot: commands.Bot) -> None:
await bot.add_cog(Playlists(bot))
2 changes: 1 addition & 1 deletion function.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ async def similar_track(player) -> bool:
tracks = []

if randomTrack.spotify:
tracks = await player.spotifyRelatedTrack(seed_artists=randomTrack.artistId[0], seed_tracks=randomTrack.track_id)
tracks = await player.spotifyRelatedTrack(randomTrack.identifier)
else:
if randomTrack.source != 'youtube':
return False
Expand Down
1 change: 0 additions & 1 deletion langs/CH.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@
"playlistShare": "抱歉!此播放清單已與 {0} 共享。",
"playlistSent": "抱歉!你已發送過邀請。",
"noPlaylistAcc": "{0} 沒有建立播放清單帳戶。",
"playlistCreateError": "抱歉!你無法建立此類型的播放清單!",
"overPlaylistCreation": "你不能建立超過 `{0}` 個播放清單!",
"playlistExists": "播放清單 [`{0}`] 已存在。",
"playlistNotInvaildUrl": "請輸入有效的連結或公開的 Spotify 或 YouTube 播放清單連結。",
Expand Down
1 change: 0 additions & 1 deletion langs/DE.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@
"playlistShare": "Es tut uns leid! Diese Playlist wurde mit {0} geteilt.",
"playlistSent": "Es tut uns leid! Sie haben bereits eine Einladung gesendet.",
"noPlaylistAcc": "{0} hat kein Playlist-Konto erstellt.",
"playlistCreateError": "Es tut uns leid! Sie können diese Art von Wiedergabeliste nicht erstellen!",
"overPlaylistCreation": "Sie können nicht mehr als `{0}` Wiedergabelisten erstellen!",
"playlistExists": "Playlist [`{0}`] existiert bereits.",
"playlistNotInvaildUrl": "Bitte geben Sie einen gültigen Link oder öffentlichen Spotify- oder YouTube-Playlist-Link ein.",
Expand Down
1 change: 0 additions & 1 deletion langs/EN.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@
"playlistShare": "Sorry! This playlist has been shared with {0}.",
"playlistSent": "Sorry! You have sent an invitation before.",
"noPlaylistAcc": "{0} didn't create a playlist account.",
"playlistCreateError": "Sorry! You are not able to create this type of playlist!",
"overPlaylistCreation": "You cannot create more than `{0}` playlists!",
"playlistExists": "Playlist [`{0}`] already exists.",
"playlistNotInvaildUrl": "Please enter a valid link or public spotify or youtube playlist link.",
Expand Down
1 change: 0 additions & 1 deletion langs/ES.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@
"playlistShare": "Lo siento! Esta lista de reproducción se ha compartido con `{0}`.",
"playlistSent": "Lo siento! Ya ha enviado una invitación antes.",
"noPlaylistAcc": "`{0}` no ha creado una cuenta de lista de reproducción.",
"playlistCreateError": "Lo siento! No puede crear este tipo de lista de reproducción.",
"overPlaylistCreation": "¡No puede crear más de `{0}` listas de reproducción!",
"playlistExists": "La lista de reproducción [`{0}`] ya existe.",
"playlistNotInvaildUrl": "Ingrese un enlace válido o un enlace público de lista de reproducción de Spotify o YouTube.",
Expand Down
1 change: 0 additions & 1 deletion langs/JA.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@
"playlistShare": "申し訳ありません!このプレイリストは{0}さんと共有されています。",
"playlistSent": "申し訳ありません!以前に招待状を送信しました。",
"noPlaylistAcc": "{0}さんはプレイリストアカウントを作成していません。",
"playlistCreateError": "申し訳ありません!この種類のプレイリストを作成することはできません!",
"overPlaylistCreation": " {0}個以上のプレイリストを作成することはできません!",
"playlistExists": "プレイリスト[{0}]はすでに存在します。",
"playlistNotInvaildUrl": "有効なリンクまたは公開SpotifyまたはYouTubeプレイリストリンクを入力してください。",
Expand Down
1 change: 0 additions & 1 deletion langs/KO.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@
"playlistShare": "죄송합니다! 이 재생 목록은 {0}과(와) 공유되었습니다.",
"playlistSent": "죄송합니다! 이미 초대장을 보냈습니다.",
"noPlaylistAcc": "{0}님은 재생 목록 계정을 만들지 않았습니다.",
"playlistCreateError": "죄송합니다! 이 유형의 재생 목록을 만들 수 없습니다!",
"overPlaylistCreation": "더 이상 {0}개 이상의 재생 목록을 만들 수 없습니다!",
"playlistExists": "재생 목록 [{0}]이(가) 이미 있습니다.",
"playlistNotInvaildUrl": "유효한 링크 또는 공개 Spotify 또는 YouTube 재생 목록 링크를 입력하세요.",
Expand Down
4 changes: 2 additions & 2 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ async def setup_hook(self):
if not func.settings.version or func.settings.version != update.__version__:
func.update_json(func.root_dir + "/settings.json", new_data={"version": update.__version__})

await bot.tree.set_translator(Translator())
await bot.tree.sync()
await self.tree.set_translator(Translator())
await self.tree.sync()

async def on_ready(self):
print("------------------")
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
discord.py==2.2.2
discord.py==2.2.3
pymongo==4.1.1
dnspython==2.2.1
tldextract==3.2.1
Expand Down
2 changes: 1 addition & 1 deletion update.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

root_dir = os.path.dirname(os.path.abspath(__file__))
install_pack_dir = os.path.join(root_dir, "Vocard.zip")
__version__ = "v2.6.3"
__version__ = "v2.6.4"

def checkVersion(withMsg = False):
resp = requests.get("https://api.github.com/repos/ChocoMeow/Vocard/releases/latest")
Expand Down
15 changes: 5 additions & 10 deletions views/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@
get_playlist,
update_playlist,
create_account,
checkroles,
formatTime
checkroles
)

from typing import Dict

def key(interaction: discord.Interaction):
Expand Down Expand Up @@ -166,15 +166,10 @@ async def callback(self, interaction: discord.Interaction):
rank, max_p, max_t = await checkroles(interaction.user.id)
if len(user['200']['tracks']) >= max_t:
return await interaction.response.send_message(self.player.get_msg("playlistlimited").format(max_t), ephemeral=True)
addtrack = {'id': track.track_id,
'info':{'identifier': track.identifier,
'author': track.author,
'length': track.length / 1000,
'title': track.title,
'uri': track.uri}}
if addtrack in user['200']['tracks']:

if track.track_id in user['200']['tracks']:
return await interaction.response.send_message(self.player.get_msg("playlistrepeated"), ephemeral=True)
respond = await update_playlist(interaction.user.id, {'playlist.200.tracks': addtrack}, push=True)
respond = await update_playlist(interaction.user.id, {'playlist.200.tracks': track.track_id}, push=True)
if respond:
await interaction.response.send_message(self.player.get_msg("playlistAdded").format(track.title, interaction.user.mention, user['200']['name']), ephemeral=True)
else:
Expand Down
5 changes: 5 additions & 0 deletions views/inbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ def __init__(self, author, inbox):
self.current = None
self.add_item(Select_message(inbox))

async def interaction_check(self, interaction):
if interaction.user == self.author:
return True
return False

def build_embed(self):
embed=discord.Embed(title=f"📭 All {self.author}'s Inbox",
description=f'Max Messages: {len(self.inbox)}/10' + '```%0s %2s %20s\n' % (" ", "ID:", "Title:") + '\n'.join('%0s %2s. %35s'% ('✉️' if mail['type'] == 'invite' else '📢', index, mail['title'][:35] + "...") for index, mail in enumerate(self.inbox, start=1)) + '```',
Expand Down
Loading

0 comments on commit 7809afe

Please sign in to comment.