From 34289bddcc9d00277ebdca2982490b59748d0a99 Mon Sep 17 00:00:00 2001 From: Sourcery AI Date: Mon, 9 May 2022 05:35:20 +0000 Subject: [PATCH] 'Refactored by Sourcery' --- espionage.py | 5 +++-- music.py | 6 +++--- start.py | 2 +- uploading.py | 6 +++--- utils.py | 38 ++++++++++++-------------------------- 5 files changed, 22 insertions(+), 35 deletions(-) diff --git a/espionage.py b/espionage.py index 2e16d6b..43d9ba9 100644 --- a/espionage.py +++ b/espionage.py @@ -24,7 +24,7 @@ def __init__(self, bot: Bot, files: Dict[str, dict], sf2s: Dict[str, str]): self.files = files self.sf2s = sf2s self.bot.event(self.on_voice_state_update) - for name in files.keys(): + for name in files: self.add_command(name) print(f"Loaded {len(files)} audio commands.") @@ -87,8 +87,9 @@ async def on_voice_state_update( # play the default file or leave the currently playing file await self.play( member.voice.channel, - cmd=ESPIONAGE_FILE if not member.guild.voice_client else None, + cmd=None if member.guild.voice_client else ESPIONAGE_FILE, ) + return # a user joined the channel when the bot was alone diff --git a/music.py b/music.py index 4a2a1b3..4eb692f 100644 --- a/music.py +++ b/music.py @@ -33,8 +33,7 @@ async def loop(self, ctx: Context, name: str = None): return cmd = await ensure_command(ctx, name, self.files) - pack = "pack" in cmd and cmd["pack"] - if pack: + if pack := "pack" in cmd and cmd["pack"]: await ctx.send( f":file_folder: `!{name}` is a music pack; try using `!random {name}` to toggle its random playback.", delete_after=10, @@ -87,9 +86,10 @@ async def speed(self, ctx: Context, name: str = None, speed: str = None): return if not midi and "info" not in cmd: await ctx.send( - f"Speed changing is not possible - missing file metadata.", + "Speed changing is not possible - missing file metadata.", delete_after=10, ) + return if speed != 100: diff --git a/start.py b/start.py index 88fea5f..500c9f5 100644 --- a/start.py +++ b/start.py @@ -27,7 +27,7 @@ async def on_ready(): def migrate(file: dict) -> bool: migrated = False - version = file["version"] if "version" in file else 1 + version = file.get("version", 1) if version < 2: # add missing author info if "author" not in file: diff --git a/uploading.py b/uploading.py index 48af7a0..c455251 100644 --- a/uploading.py +++ b/uploading.py @@ -43,8 +43,7 @@ async def pack(self, ctx: Context, name: str = None): cmd = await ensure_command(ctx, name, self.files) await ensure_can_modify(ctx, cmd) - pack = "pack" in cmd and cmd["pack"] - if pack: + if pack := "pack" in cmd and cmd["pack"]: await ctx.send(f"`!{name}` is already a music pack.", delete_after=3) return @@ -251,7 +250,7 @@ async def upload(self, ctx: Context, name: str = None): # save cmd for new pack or replaced file if not pack or not existing: cmd = { - "filename": basename(filename if not pack else dirname), + "filename": basename(dirname if pack else filename), "help": f"Uploaded by {ctx.author}", "loop": True, "author": { @@ -260,6 +259,7 @@ async def upload(self, ctx: Context, name: str = None): }, "version": CMD_VERSION, } + fill_audio_info(cmd) # save filtering flags diff --git a/utils.py b/utils.py index aa822b2..ba3f64d 100644 --- a/utils.py +++ b/utils.py @@ -28,11 +28,7 @@ UPLOAD_PATH, ) -if sys.platform != "win32": - CREATE_NO_WINDOW = 0 -else: - CREATE_NO_WINDOW = 0x08000000 - +CREATE_NO_WINDOW = 0 if sys.platform != "win32" else 0x08000000 archive_mimetypes = [ "application/zip", "application/x-rar-compressed", @@ -50,11 +46,7 @@ class FFmpegFileOpusAudio(FFmpegOpusAudio): def __init__(self, filename: str, rate: int, *args, **kwargs): self.filename = filename - if rate: - opts = f"-af asetrate={rate}" - else: - opts = "" - + opts = f"-af asetrate={rate}" if rate else "" super().__init__(filename, options=opts, *args, **kwargs) @@ -74,11 +66,7 @@ def __init__(self, filename: str, soundfont: str, rate: int, *args, **kwargs): else: before_opts = [] - if rate: - opts = f"-af asetrate={rate},aformat=channel_layouts=2" - else: - opts = "" - + opts = f"-af asetrate={rate},aformat=channel_layouts=2" if rate else "" super().__init__( "-", before_options=" ".join(before_opts), options=opts, *args, **kwargs ) @@ -123,14 +111,13 @@ def _get_args_tm(self) -> List[str]: if MIDI_MUTE_124: opts.append("font exclude 0 124") opts = "\\n".join(opts) - args = [ + return [ "timidity", f'-x "{opts}"', # Configure TiMidity++ with str "-Ow", # Generate RIFF WAVE format output "-o -", # Place output on file quote(self.filename), ] - return args def _spawn_process(self, args, **subprocess_kwargs): process = None @@ -141,7 +128,7 @@ def _spawn_process(self, args, **subprocess_kwargs): ) except FileNotFoundError: executable = args.partition(" ")[0] if isinstance(args, str) else args[0] - raise ClientException(executable + " was not found.") from None + raise ClientException(f"{executable} was not found.") from None except subprocess.SubprocessError as exc: raise ClientException( "Popen failed: {0.__class__.__name__}: {0}".format(exc) @@ -163,9 +150,7 @@ async def connect_to(channel: VoiceChannel) -> VoiceClient: def is_alone(voice: VoiceClient) -> bool: - if not voice: - return False - return len(voice.channel.voice_states) <= 1 + return len(voice.channel.voice_states) <= 1 if voice else False async def disconnect(voice: VoiceClient): @@ -175,7 +160,7 @@ async def disconnect(voice: VoiceClient): async def ensure_voice(_, ctx: Context): member: Member = len(ctx.args) > 2 and ctx.args[2] or ctx.author if not member.voice: - await ctx.send(f"User is not connected to a voice channel.", delete_after=3) + await ctx.send("User is not connected to a voice channel.", delete_after=3) raise CommandError(f"{ctx.author} not connected to a voice channel.") await connect_to(member.voice.channel) @@ -189,9 +174,10 @@ async def ensure_can_modify(ctx: Context, cmd: dict): ) if not can_remove: await ctx.send( - f"Only the author of the file or an admin can modify/remove it.", + "Only the author of the file or an admin can modify/remove it.", delete_after=3, ) + raise CommandError(f"File {cmd} is not modifiable by {ctx.author}") @@ -226,13 +212,13 @@ def filetype(filename: str) -> str: def check_file(filename: str) -> Tuple[bool, bool, bool, bool, bool]: mime_type, mime_text = filetype(filename) - soundfont = "audio/x-sfbk" == mime_type or "SoundFont/Bank" in mime_text + soundfont = mime_type == "audio/x-sfbk" or "SoundFont/Bank" in mime_text if soundfont: return False, False, True, False, False audio = mime_type.startswith("audio/") video = mime_type.startswith("video/") archive = mime_type in archive_mimetypes - midi = "audio/midi" == mime_type + midi = mime_type == "audio/midi" return audio or video, archive, soundfont, midi, video @@ -247,7 +233,7 @@ def get_audio_info(filename: str) -> Union[dict, None]: result = subprocess.run(split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE) data = result.stdout.decode() data = json.loads(data) - if not "streams" in data: + if "streams" not in data: return None data = [s for s in data["streams"] if s["codec_type"] == "audio"] if not data: