General clean code

This commit is contained in:
Choco
2023-08-26 09:48:36 +08:00
parent e287a3cf8c
commit b7456f5312
12 changed files with 119 additions and 137 deletions

View File

@@ -191,8 +191,8 @@ class Basic(commands.Cog):
embed = discord.Embed(title=player.get_msg('searchTitle').format(query), description=player.get_msg(
'searchDesc').format(emoji_source(platform), platform, len(tracks[0:10]), query_track), color=settings.embed_color)
view = SearchView(tracks=tracks[0:10], lang=player.get_msg)
message = await ctx.send(embed=embed, view=view, ephemeral=True)
view.response = message
view.response = await ctx.send(embed=embed, view=view, ephemeral=True)
await view.wait()
if view.values is not None:
msg = ""
@@ -432,8 +432,7 @@ class Basic(commands.Cog):
if player.queue.is_empty:
return await nowplay(ctx, player)
view = ListView(player=player, author=ctx.author)
message = await ctx.send(embed=view.build_embed(), view=view)
view.response = message
view.response = await ctx.send(embed=view.build_embed(), view=view)
@queue.command(name="export", aliases=get_aliases("export"))
@commands.dynamic_cooldown(cooldown_check, commands.BucketType.guild)
@@ -520,8 +519,7 @@ class Basic(commands.Cog):
return await nowplay(ctx, player)
view = ListView(player=player, author=ctx.author, isQueue=False)
message = await ctx.send(embed=view.build_embed(), view=view)
view.response = message
view.response = await ctx.send(embed=view.build_embed(), view=view)
@commands.hybrid_command(name="leave", aliases=get_aliases("leave"))
@commands.dynamic_cooldown(cooldown_check, commands.BucketType.guild)
@@ -776,8 +774,7 @@ class Basic(commands.Cog):
return await ctx.send(get_lang(ctx.guild.id, 'lyricsNotFound'), ephemeral=True)
view = LyricsView(name=name, source={_: re.findall(r'.*\n(?:.*\n){,22}', v) for _, v in song.items()}, author=ctx.author)
message = await ctx.send(embed=view.build_embed(), view=view)
view.response = message
view.response = await ctx.send(embed=view.build_embed(), view=view)
@commands.hybrid_command(name="swapdj", aliases=get_aliases("swapdj"))
@app_commands.describe(member="Choose a member to transfer the dj role.")
@@ -839,8 +836,7 @@ class Basic(commands.Cog):
return await ctx.send(player.get_msg('noChaptersFound'), ephemeral=True)
view = ChapterView(player, chapters, author=ctx.author)
message = await ctx.send(view=view)
view.response = message
view.response = await ctx.send(view=view)
@commands.hybrid_command(name="autoplay", aliases=get_aliases("autoplay"))
@commands.dynamic_cooldown(cooldown_check, commands.BucketType.guild)

View File

@@ -12,7 +12,7 @@ from function import (
update_playlist,
update_inbox,
get_lang,
playlist_name,
PLAYLIST_NAME,
settings,
get_aliases,
cooldown_check
@@ -70,10 +70,10 @@ class Playlists(commands.Cog, name="playlist"):
self.description = "This is the Vocard playlist system. You can save your favorites and use Vocard to play on any server."
async def playlist_autocomplete(self, interaction: discord.Interaction, current: str) -> list:
playlists = playlist_name.get(str(interaction.user.id), None)
playlists = PLAYLIST_NAME.get(str(interaction.user.id), None)
if not playlists:
playlists_raw = await get_playlist(interaction.user.id, 'playlist')
playlists = playlist_name[str(interaction.user.id)] = [
playlists = PLAYLIST_NAME[str(interaction.user.id)] = [
value['name'] for value in playlists_raw.values()] if playlists_raw else []
if current:
return [app_commands.Choice(name=p, value=p) for p in playlists if current in p]
@@ -87,8 +87,7 @@ class Playlists(commands.Cog, name="playlist"):
async def playlist(self, ctx: commands.Context):
view = HelpView(self.bot, ctx.author)
embed = view.build_embed(self.qualified_name)
message = await ctx.send(embed=embed, view=view)
view.response = message
view.response = await ctx.send(embed=embed, view=view)
@playlist.command(name="play", aliases=get_aliases("play"))
@app_commands.describe(
@@ -104,7 +103,7 @@ class Playlists(commands.Cog, name="playlist"):
return await create_account(ctx)
if not result['playlist']:
return await ctx.send(get_lang(ctx.guild.id, 'playlistNotFound').format(name), ephemeral=True)
rank, max_p, max_t = await checkroles(ctx.author.id)
rank, max_p, max_t = await checkroles()
if result['position'] > max_p:
return await ctx.send(get_lang(ctx.guild.id, 'playlistNotAccess'), ephemeral=True)
@@ -142,7 +141,7 @@ class Playlists(commands.Cog, name="playlist"):
user = await check_playlist(ctx, full=True)
if not user:
return await create_account(ctx)
rank, max_p, max_t = await checkroles(ctx.author.id)
rank, max_p, max_t = await checkroles()
results = []
for index, data in enumerate(user, start=1):
@@ -156,7 +155,7 @@ class Playlists(commands.Cog, name="playlist"):
if share := playlist['type'] == 'share':
playlist = await check_playlist_perms(ctx.author.id, playlist['user'], playlist['referId'])
if not playlist:
await update_playlist(ctx.author.id, {f"playlist.{data}": 1}, mode=False)
await update_playlist(ctx.author.id, {f"playlist.{data}": 1}, mode="unset")
continue
if playlist['type'] == 'link':
tracks = await search_playlist(playlist['uri'], requester=ctx.author)
@@ -196,7 +195,7 @@ class Playlists(commands.Cog, name="playlist"):
if len(name) > 10:
return await ctx.send(get_lang(ctx.guild.id, 'playlistOverText'), ephemeral=True)
rank, max_p, max_t = await checkroles(ctx.author.id)
rank, max_p, max_t = await checkroles()
user = await check_playlist(ctx, full=True)
if not user:
return await create_account(ctx)
@@ -212,9 +211,8 @@ class Playlists(commands.Cog, name="playlist"):
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 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 update_playlist(ctx.author.id, {f"playlist.{assign_playlistId([data for data in user])}": data}, update_cache=True)
await ctx.send(get_lang(ctx.guild.id, 'playlistCreated').format(name))
@playlist.command(name="delete", aliases=get_aliases("delete"))
@@ -232,10 +230,9 @@ class Playlists(commands.Cog, name="playlist"):
return await ctx.send(get_lang(ctx.guild.id, 'playlistDeleteError'), ephemeral=True)
if result['playlist']['type'] == 'share':
await update_playlist(result['playlist']['user'], {f"playlist.{result['playlist']['referId']}.perms.read": ctx.author.id}, pull=True, mode=False)
await update_playlist(result['playlist']['user'], {f"playlist.{result['playlist']['referId']}.perms.read": ctx.author.id}, mode="pull")
playlist_name.pop(str(ctx.author.id), None)
await update_playlist(ctx.author.id, {f"playlist.{result['id']}": 1}, mode=False)
await update_playlist(ctx.author.id, {f"playlist.{result['id']}": 1}, mode="unset", update_cache=True)
return await ctx.send(get_lang(ctx.guild.id, 'playlistRemove').format(result['playlist']['name']))
@playlist.command(name="share", aliases=get_aliases("share"))
@@ -300,8 +297,7 @@ class Playlists(commands.Cog, name="playlist"):
if not found:
return await ctx.send(get_lang(ctx.guild.id, 'playlistNotFound').format(name), ephemeral=True)
playlist_name.pop(str(ctx.author.id), None)
await update_playlist(ctx.author.id, {f'playlist.{id}.name': newname})
await update_playlist(ctx.author.id, {f'playlist.{id}.name': newname}, update_cache=True)
await ctx.send(get_lang(ctx.guild.id, 'playlistRenamed').format(name, newname))
@playlist.command(name="inbox", aliases=get_aliases("inbox"))
@@ -316,8 +312,7 @@ class Playlists(commands.Cog, name="playlist"):
inbox = user['inbox'].copy()
view = InboxView(ctx.author, user['inbox'])
message = await ctx.send(embed=view.build_embed(), view=view, ephemeral=True)
view.response = message
view.response = await ctx.send(embed=view.build_embed(), view=view, ephemeral=True)
await view.wait()
if inbox == user['inbox']:
@@ -325,13 +320,12 @@ class Playlists(commands.Cog, name="playlist"):
updateData, dId = {}, {dId for dId in user["playlist"]}
for data in view.newplaylist[:(5 - len(user['playlist']))]:
addId = assign_playlistId(dId)
await update_playlist(data['sender'], {f"playlist.{data['referId']}.perms.read": ctx.author.id}, push=True)
await update_playlist(data['sender'], {f"playlist.{data['referId']}.perms.read": ctx.author.id}, mode="push")
updateData[f'playlist.{addId}'] = {'user': data['sender'], 'referId': data['referId'],
'name': f"Share{data['time'].strftime('%M%S')}", 'type': 'share'}
dId.add(addId)
playlist_name.pop(str(ctx.author.id), None)
await update_playlist(ctx.author.id, updateData | {'inbox': view.inbox})
await update_playlist(ctx.author.id, updateData | {'inbox': view.inbox}, update_cache=True)
@playlist.command(name="add", aliases=get_aliases("add"))
@commands.dynamic_cooldown(cooldown_check, commands.BucketType.guild)
@@ -350,7 +344,7 @@ class Playlists(commands.Cog, name="playlist"):
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)
rank, max_p, max_t = await checkroles()
if len(result['playlist']['tracks']) >= max_t:
return await ctx.send(get_lang(ctx.guild.id, 'playlistLimitTrack').format(max_t), ephemeral=True)
@@ -364,7 +358,7 @@ class Playlists(commands.Cog, name="playlist"):
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': results[0].track_id}, push=True)
await update_playlist(ctx.author.id, {f'playlist.{result["id"]}.tracks': results[0].track_id}, mode="push")
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"))
@@ -386,7 +380,7 @@ class Playlists(commands.Cog, name="playlist"):
if not 0 < position <= len(result['playlist']['tracks']):
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 update_playlist(ctx.author.id, {f'playlist.{result["id"]}.tracks': result['playlist']['tracks'][position - 1]}, mode="pull")
track = voicelink.decode(result['playlist']['tracks'][position - 1])
await ctx.send(get_lang(ctx.guild.id, 'playlistRemoved').format(track.get("title"), ctx.author, name))
@@ -462,7 +456,7 @@ class Playlists(commands.Cog, name="playlist"):
if len(name) > 10:
return await ctx.send(get_lang(ctx.guild.id, 'playlistOverText'), ephemeral=True)
rank, max_p, max_t = await checkroles(ctx.author.id)
rank, max_p, max_t = await checkroles()
user = await check_playlist(ctx, full=True)
if not user:
return await create_account(ctx)
@@ -479,9 +473,8 @@ class Playlists(commands.Cog, name="playlist"):
track_ids = bytes.split(b"\n")[-1]
track_ids = track_ids.decode().split(",")
playlist_name.pop(str(ctx.author.id), None)
data = {'tracks': track_ids, '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 update_playlist(ctx.author.id, {f"playlist.{assign_playlistId([data for data in user])}": data}, update_cache=True)
await ctx.send(get_lang(ctx.guild.id, 'playlistCreated').format(name))
except:

View File

@@ -7,7 +7,7 @@ from typing import Tuple
from discord import app_commands
from discord.ext import commands
from function import (
langs,
LANGS,
update_settings,
get_settings,
get_lang,
@@ -47,8 +47,7 @@ class Settings(commands.Cog, name="settings"):
async def settings(self, ctx: commands.Context):
view = HelpView(self.bot, ctx.author)
embed = view.build_embed(self.qualified_name)
message = await ctx.send(embed=embed, view=view)
view.response = message
view.response = await ctx.send(embed=embed, view=view)
@settings.command(name="prefix", aliases=get_aliases("prefix"))
@commands.has_permissions(manage_guild=True)
@@ -64,7 +63,7 @@ class Settings(commands.Cog, name="settings"):
async def language(self, ctx: commands.Context, language: str):
"You can choose your preferred language, the bot message will change to the language you set."
language = language.upper()
if language not in langs:
if language not in LANGS:
return await ctx.send(get_lang(ctx.guild.id, "languageNotFound"))
update_settings(ctx.guild.id, {'lang': language})
@@ -73,8 +72,8 @@ class Settings(commands.Cog, name="settings"):
@language.autocomplete('language')
async def autocomplete_callback(self, interaction: discord.Interaction, current: str) -> list:
if current:
return [app_commands.Choice(name=lang, value=lang) for lang in langs.keys() if current.upper() in lang]
return [app_commands.Choice(name=lang, value=lang) for lang in langs.keys()]
return [app_commands.Choice(name=lang, value=lang) for lang in LANGS.keys() if current.upper() in lang]
return [app_commands.Choice(name=lang, value=lang) for lang in LANGS.keys()]
@settings.command(name="dj", aliases=get_aliases("dj"))
@commands.has_permissions(manage_guild=True)
@@ -86,7 +85,7 @@ class Settings(commands.Cog, name="settings"):
if not role:
if player:
player.settings.pop('dj', None)
update_settings(ctx.guild.id, {'dj': ''}, mode="Unset")
update_settings(ctx.guild.id, {'dj': ''}, mode="unset")
else:
if player:
player.settings['dj'] = role.id
@@ -229,8 +228,7 @@ class Settings(commands.Cog, name="settings"):
controller_settings = settings.get("default_controller", func.settings.controller)
view = EmbedBuilderView(ctx.author, controller_settings.get("embeds").copy())
message = await ctx.send(embed=view.build_embed(), view=view)
view.response = message
view.response = await ctx.send(embed=view.build_embed(), view=view)
@settings.command(name="controllermsg", aliases=get_aliases("controllermsg"))
@commands.has_permissions(manage_guild=True)

View File

@@ -87,8 +87,8 @@ class Task(commands.Cog):
@tasks.loop(hours=12.0)
async def cache_cleaner(self):
func.guild_settings.clear()
func.playlist_name.clear()
func.GUILD_SETTINGS.clear()
func.PLAYLIST_NAME.clear()
errorFile = func.gen_report()
if errorFile:
@@ -98,7 +98,7 @@ class Task(commands.Cog):
await report_channel.send(content=f"Report Before: <t:{round(datetime.timestamp(datetime.now()))}:F>", file=errorFile)
except Exception as e:
print(f"Report could not be sent (Reason: {e})")
func.error_log.clear()
func.ERROR_LOGS.clear()
async def setup(bot: commands.Bot):
await bot.add_cog(Task(bot))

View File

@@ -8,12 +8,12 @@ from datetime import datetime
from time import strptime
from io import BytesIO
from pymongo import MongoClient
from typing import Optional, Union
from typing import Optional, Union, Any
from addons import Settings, TOKENS
root_dir = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
if not os.path.exists(os.path.join(root_dir, "settings.json")):
if not os.path.exists(os.path.join(ROOT_DIR, "settings.json")):
raise Exception("Settings file not set!")
#-------------- API Clients --------------
@@ -32,45 +32,46 @@ try:
except Exception as e:
raise Exception("Not able to connect MongoDB! Reason:", e)
collection = mongodb[tokens.mongodb_name]['Settings']
Playlist = mongodb[tokens.mongodb_name]['Playlist']
SETTINGS_DB = mongodb[tokens.mongodb_name]['Settings']
PLAYLISTS_DB = mongodb[tokens.mongodb_name]['Playlist']
#--------------- Cache Var ---------------
settings: Settings
error_log = {} #Stores error that not a Voicelink Exception
langs = {} #Stores all the languages in ./langs
guild_settings = {} #Cache guild language
local_langs = {} #Stores all the localization languages in ./local_langs
playlist_name = {} #Cache the user's playlist name
ERROR_LOGS: dict[int, dict[int, str]] = {} #Stores error that not a Voicelink Exception
LANGS: dict[str, dict[str, str]] = {} #Stores all the languages in ./langs
GUILD_SETTINGS: dict[int, dict[str, Any]] = {} #Cache guild language
LOCAL_LANGS: dict[str, dict[str, str]] = {} #Stores all the localization languages in ./local_langs
PLAYLIST_NAME: dict[str, list[str]] = {} #Cache the user's playlist name
#-------------- Vocard Functions --------------
def get_settings(guild_id:int) -> dict:
settings = guild_settings.get(guild_id, None)
settings = GUILD_SETTINGS.get(guild_id, None)
if not settings:
settings = collection.find_one({"_id":guild_id})
settings = SETTINGS_DB.find_one({"_id":guild_id})
if not settings:
collection.insert_one({"_id":guild_id})
settings = {}
guild_settings[guild_id] = settings
SETTINGS_DB.insert_one({"_id":guild_id})
GUILD_SETTINGS[guild_id] = settings or {}
return settings
def update_settings(guild_id:int, data: dict, mode="Set") -> None:
def update_settings(guild_id:int, data: dict, mode="set") -> None:
settings = get_settings(guild_id)
if mode == "Set":
for key, value in data.items():
if settings.get(key) != value:
guild_settings[guild_id][key] = value
collection.update_one({"_id":guild_id}, {"$set":data})
elif mode == "Delete":
for key, value in data.items():
if settings.get(key) != value:
del guild_settings[guild_id][key]
collection.update_one({"_id":guild_id}, {"$unset":data})
return
for key, value in data.items():
if settings.get(key) != value:
match mode:
case "set":
GUILD_SETTINGS[guild_id][key] = value
case "unset":
GUILD_SETTINGS[guild_id].pop(key)
case _:
return
SETTINGS_DB.update_one({"_id":guild_id}, {f"${mode}":data})
def open_json(path: str) -> dict:
try:
with open(os.path.join(root_dir, path), encoding="utf8") as json_file:
with open(os.path.join(ROOT_DIR, path), encoding="utf8") as json_file:
return json.load(json_file)
except:
return {}
@@ -82,15 +83,15 @@ def update_json(path: str, new_data: dict) -> None:
data.update(new_data)
with open(os.path.join(root_dir, path), "w") as json_file:
with open(os.path.join(ROOT_DIR, path), "w") as json_file:
json.dump(data, json_file, indent=4)
def get_lang(guild_id:int, key:str) -> str:
lang = get_settings(guild_id).get("lang", "EN")
if lang in langs and not langs[lang]:
langs[lang] = open_json(os.path.join("langs", f"{lang}.json"))
if lang in LANGS and not LANGS[lang]:
LANGS[lang] = open_json(os.path.join("langs", f"{lang}.json"))
return langs.get(lang, {}).get(key, "Language pack not found!")
return LANGS.get(lang, {}).get(key, "Language pack not found!")
def init() -> None:
global settings
@@ -100,13 +101,13 @@ def init() -> None:
settings = Settings(json)
def langs_setup() -> None:
for language in os.listdir(os.path.join(root_dir, "langs")):
for language in os.listdir(os.path.join(ROOT_DIR, "langs")):
if language.endswith('.json'):
langs[language[:-5]] = {}
LANGS[language[:-5]] = {}
for language in os.listdir(os.path.join(root_dir, "local_langs")):
for language in os.listdir(os.path.join(ROOT_DIR, "local_langs")):
if language.endswith('.json'):
local_langs[language[:-5]] = open_json(os.path.join("local_langs", language))
LOCAL_LANGS[language[:-5]] = open_json(os.path.join("local_langs", language))
return
@@ -137,9 +138,9 @@ def emoji_source(emoji:str) -> str:
return settings.emoji_source_raw.get(emoji.lower(), "🔗")
def gen_report() -> Optional[discord.File]:
if error_log:
if ERROR_LOGS:
errorText = ""
for guild_id, error in error_log.items():
for guild_id, error in ERROR_LOGS.items():
errorText += f"Guild ID: {guild_id}\n" + "-" * 30 + "\n"
for index, (key, value) in enumerate(error.items() , start=1):
errorText += f"Error No: {index}, Time: {datetime.fromtimestamp(key)}\n" + value + "-" * 30 + "\n\n"
@@ -183,20 +184,19 @@ async def create_account(ctx: Union[commands.Context, discord.Interaction]) -> N
" ➥ You have the right to immediately stop the services we offer to you\n"
" ➥ Please do not abuse our services, such as affecting other users\n", inline=False)
if isinstance(ctx, commands.Context):
message = await ctx.reply(embed=embed, view=view, ephemeral=True)
view.response = await ctx.reply(embed=embed, view=view, ephemeral=True)
else:
message = await ctx.response.send_message(embed=embed, view=view, ephemeral=True)
view.response = await ctx.response.send_message(embed=embed, view=view, ephemeral=True)
view.response = message
await view.wait()
if view.value:
try:
Playlist.insert_one({'_id':author.id, 'playlist': {'200':{'tracks':[],'perms':{ 'read': [], 'write':[], 'remove': []},'name':'Favourite', 'type':'playlist' }},'inbox':[] })
PLAYLISTS_DB.insert_one({'_id':author.id, 'playlist': {'200':{'tracks':[],'perms':{ 'read': [], 'write':[], 'remove': []},'name':'Favourite', 'type':'playlist' }},'inbox':[] })
except:
pass
async def get_playlist(userid:int, dType:str=None, dId:str=None) -> dict:
user = Playlist.find_one({"_id":userid}, {"_id": 0})
async def get_playlist(user_id:int, dType:str=None, dId:str=None) -> dict:
user = PLAYLISTS_DB.find_one({"_id":user_id}, {"_id": 0})
if not user:
return None
if dType:
@@ -205,21 +205,13 @@ async def get_playlist(userid:int, dType:str=None, dId:str=None) -> dict:
return user[dType]
return user
async def update_playlist(userid:int, data:dict=None, push=False, pull=False, mode=True) -> None:
if mode is True:
if push:
return Playlist.update_one({"_id":userid}, {"$push": data})
Playlist.update_one({"_id":userid}, {"$set": data})
else:
if pull:
return Playlist.update_one({"_id":userid}, {"$pull": data})
Playlist.update_one({"_id":userid}, {"$unset": data})
return
async def update_playlist(user_id:int, data:dict, *, mode:str="set", update_cache: bool=False) -> None:
if update_cache:
PLAYLIST_NAME.pop(str(user_id), None)
PLAYLISTS_DB.update_one({"_id":user_id}, {f"${mode}": data})
async def update_inbox(userid:int, data:dict) -> None:
return Playlist.update_one({"_id":userid}, {"$push":{'inbox':data}})
async def update_inbox(user_id:int, data:dict) -> None:
return PLAYLISTS_DB.update_one({"_id":user_id}, {"$push":{'inbox':data}})
async def checkroles(userid:int):
rank, max_p, max_t = 'Normal', 5, 500
return rank, max_p, max_t
async def checkroles():
return 'Normal', 5, 500

14
main.py
View File

@@ -21,8 +21,8 @@ class Translator(discord.app_commands.Translator):
print("Unload Translator")
async def translate(self, string: discord.app_commands.locale_str, locale: discord.Locale, context: discord.app_commands.TranslationContext):
if str(locale) in func.local_langs:
return func.local_langs[str(locale)].get(string.message, None)
if str(locale) in func.LOCAL_LANGS:
return func.LOCAL_LANGS[str(locale)].get(string.message, None)
return None
class Vocard(commands.Bot):
@@ -50,7 +50,7 @@ class Vocard(commands.Bot):
async def setup_hook(self):
func.langs_setup()
for module in os.listdir(func.root_dir + '/cogs'):
for module in os.listdir(func.ROOT_DIR + '/cogs'):
if module.endswith('.py'):
try:
await self.load_extension(f"cogs.{module[:-3]}")
@@ -77,7 +77,7 @@ class Vocard(commands.Bot):
print("------------------")
func.tokens.client_id = self.user.id
func.local_langs.clear()
func.LOCAL_LANGS.clear()
async def on_command_error(self, ctx: commands.Context, exception, /) -> None:
error = getattr(exception, 'original', exception)
@@ -96,9 +96,9 @@ class Vocard(commands.Bot):
elif not issubclass(error.__class__, VoicelinkException):
error = func.get_lang(ctx.guild.id, "unknownException") + func.settings.invite_link
if (guildId := ctx.guild.id) not in func.error_log:
func.error_log[guildId] = {}
func.error_log[guildId][round(datetime.timestamp(datetime.now()))] = "".join(traceback.format_exception(type(exception), exception, exception.__traceback__))
if (guildId := ctx.guild.id) not in func.ERROR_LOGS:
func.ERROR_LOGS[guildId] = {}
func.ERROR_LOGS[guildId][round(datetime.timestamp(datetime.now()))] = "".join(traceback.format_exception(type(exception), exception, exception.__traceback__))
try:
return await ctx.reply(error, ephemeral=True)

View File

@@ -1,8 +1,8 @@
import requests, zipfile, os, shutil, argparse
from io import BytesIO
root_dir = os.path.dirname(os.path.abspath(__file__))
__version__ = "v2.6.6"
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
__version__ = "v2.6.6b3"
GITHUB_API_URL = "https://api.github.com/repos/ChocoMeow/Vocard/releases/latest"
VOCARD_URL = "https://github.com/ChocoMeow/Vocard/archive/"
@@ -65,22 +65,22 @@ def install(response, version):
if user_input.lower() in ["y", "yes"]:
print("Installing ...")
zfile = zipfile.ZipFile(BytesIO(response.content))
zfile.extractall(root_dir)
zfile.extractall(ROOT_DIR)
version = version.replace("v", "")
source_dir = os.path.join(root_dir, f"Vocard-{version}")
source_dir = os.path.join(ROOT_DIR, f"Vocard-{version}")
if os.path.exists(source_dir):
for filename in os.listdir(root_dir):
for filename in os.listdir(ROOT_DIR):
if filename in IGNORE_FILES + [f"Vocard-{version}"]:
continue
filename = os.path.join(root_dir, filename)
filename = os.path.join(ROOT_DIR, filename)
if os.path.isdir(filename):
shutil.rmtree(filename)
else:
os.remove(filename)
for filename in os.listdir(source_dir):
shutil.move(os.path.join(source_dir, filename), os.path.join(root_dir, filename))
shutil.move(os.path.join(source_dir, filename), os.path.join(ROOT_DIR, filename))
os.rmdir(source_dir)
print(f"{bcolors.OKGREEN}Version {version} installed Successfully! Run `python main.py` to start your bot{bcolors.ENDC}")
else:

View File

@@ -200,13 +200,13 @@ class Add(ControlButton):
user = await get_playlist(interaction.user.id, 'playlist')
if not user:
return await create_account(interaction)
rank, max_p, max_t = await checkroles(interaction.user.id)
rank, max_p, max_t = await checkroles()
if len(user['200']['tracks']) >= max_t:
return await self.send(interaction, self.player.get_msg("playlistlimited").format(max_t), ephemeral=True)
if track.track_id in user['200']['tracks']:
return await self.send(interaction, self.player.get_msg("playlistrepeated"), ephemeral=True)
respond = await update_playlist(interaction.user.id, {'playlist.200.tracks': track.track_id}, push=True)
respond = await update_playlist(interaction.user.id, {'playlist.200.tracks': track.track_id}, mode="push")
if respond:
await self.send(interaction, self.player.get_msg("playlistAdded").format(track.title, interaction.user.mention, user['200']['name']), ephemeral=True)
else:

View File

@@ -184,7 +184,7 @@ class DebugView(discord.ui.View):
@discord.ui.button(label='Send Logs', emoji="📥", style=discord.ButtonStyle.red)
async def send_error_logs(self, interaction: discord.Interaction, button: discord.ui.Button):
if not function.error_log:
if not function.ERROR_LOGS:
return await interaction.response.send_message("Sorry there are not error logs!", ephemeral=True)
await interaction.response.send_message(file=function.gen_report(), ephemeral=True)

View File

@@ -31,14 +31,17 @@ class ListView(discord.ui.View):
super().__init__(timeout=60)
self.player = player
self.name = player.get_msg('queueTitle') if isQueue else player.get_msg('historyTitle')
self.tracks = player.queue.tracks() if isQueue else player.queue.history()
self.name: str = player.get_msg('queueTitle') if isQueue else player.get_msg('historyTitle')
self.tracks: list = player.queue.tracks() if isQueue else player.queue.history()
self.response: discord.Message = None
if not isQueue:
self.tracks.reverse()
self.author = author
self.author: discord.Member = author
self.page = ceil(len(self.tracks) / 7)
self.current_page = 1
try:
self.time = func.time(sum([track.length for track in self.tracks]))
except:

View File

@@ -23,7 +23,7 @@ SOFTWARE.
import discord
from function import langs
from function import LANGS
class SearchDropdown(discord.ui.Select):
def __init__(self, tracks, get_msg):

View File

@@ -279,7 +279,7 @@ async def getPlaylists(member: Member, data: dict):
playlist = await func.get_playlist(pList["user"], "playlist", pList["referId"])
if playlist:
if member.id not in playlist["perms"]["read"]:
await func.update_playlist(member.id, {f"playlist.{pId}": 1}, mode=False)
await func.update_playlist(member.id, {f"playlist.{pId}": 1}, mode="unset")
del playlists[pId]
continue
@@ -304,9 +304,9 @@ async def removePlaylist(member: Member, data:dict):
if isShare:
refer_user = data.get("refer_user")
await func.update_playlist(refer_user, {f"playlist.{pId}.perms.read": member.id}, pull=True, mode=False)
await func.update_playlist(refer_user, {f"playlist.{pId}.perms.read": member.id}, mode="pull")
await func.update_playlist(member.id, {f'playlist.{pId}': 1}, mode=False)
await func.update_playlist(member.id, {f'playlist.{pId}': 1}, mode="unset")
async def addPlaylistTrack(member: Member, data: dict):
track_id = data.get("track_id")
@@ -321,14 +321,14 @@ async def addPlaylistTrack(member: Member, data: dict):
if playlist["type"] != "playlist":
return error_msg(func.get_lang(member.guild.id, 'playlistNotAllow'), user_id=member.id)
rank, max_p, max_t = await func.checkroles(member.id)
rank, max_p, max_t = await func.checkroles()
if len(playlist["tracks"]) >= max_t:
return error_msg(func.get_lang(member.guild.id, "playlistlimited").format(max_t), user_id=member.id)
if track_id in playlist['tracks']:
return error_msg(func.get_lang(member.guild.id, "playlistrepeated"), user_id=member.id)
await func.update_playlist(member.id, {f'playlist.{pId}.tracks': track_id}, push=True)
await func.update_playlist(member.id, {f'playlist.{pId}.tracks': track_id}, mode="push")
async def removePlaylistTrack(member: Member, data: dict):
track_id = data.get("track_id")
@@ -336,7 +336,7 @@ async def removePlaylistTrack(member: Member, data: dict):
if not track_id or not pId:
return
await func.update_playlist(member.id, {f'playlist.{pId}.tracks': track_id }, pull=True, mode=False)
await func.update_playlist(member.id, {f'playlist.{pId}.tracks': track_id }, mode="pull")
methods = {
"initPlayer": [initPlayer, False],