Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sourcery Starbot ⭐ refactored kuba2k2/espionage-bot #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions espionage.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Espionage.__init__ refactored with the following changes:

self.add_command(name)
print(f"Loaded {len(files)} audio commands.")

Expand Down Expand Up @@ -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,
)

Comment on lines -90 to +92
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Espionage.on_voice_state_update refactored with the following changes:

return

# a user joined the channel when the bot was alone
Expand Down
6 changes: 3 additions & 3 deletions music.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Music.loop refactored with the following changes:

await ctx.send(
f":file_folder: `!{name}` is a music pack; try using `!random {name}` to toggle its random playback.",
delete_after=10,
Expand Down Expand Up @@ -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,
)

Comment on lines -90 to +92
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Music.speed refactored with the following changes:

return

if speed != 100:
Expand Down
2 changes: 1 addition & 1 deletion start.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function migrate refactored with the following changes:

  • Simplify dictionary access using default get (default-get)

if version < 2:
# add missing author info
if "author" not in file:
Expand Down
6 changes: 3 additions & 3 deletions uploading.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Uploading.pack refactored with the following changes:

await ctx.send(f"`!{name}` is already a music pack.", delete_after=3)
return

Expand Down Expand Up @@ -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),
Comment on lines -254 to +253
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Uploading.upload refactored with the following changes:

"help": f"Uploaded by {ctx.author}",
"loop": True,
"author": {
Expand All @@ -260,6 +259,7 @@ async def upload(self, ctx: Context, name: str = None):
},
"version": CMD_VERSION,
}

fill_audio_info(cmd)

# save filtering flags
Expand Down
38 changes: 12 additions & 26 deletions utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 31-35 refactored with the following changes:

archive_mimetypes = [
"application/zip",
"application/x-rar-compressed",
Expand All @@ -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 ""
Comment on lines -53 to +49
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function FFmpegFileOpusAudio.__init__ refactored with the following changes:

super().__init__(filename, options=opts, *args, **kwargs)


Expand All @@ -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 ""
Comment on lines -77 to +69
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function FFmpegMidiOpusAudio.__init__ refactored with the following changes:

super().__init__(
"-", before_options=" ".join(before_opts), options=opts, *args, **kwargs
)
Expand Down Expand Up @@ -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
Comment on lines -126 to -133
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function FFmpegMidiOpusAudio._get_args_tm refactored with the following changes:


def _spawn_process(self, args, **subprocess_kwargs):
process = None
Expand All @@ -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
Comment on lines -144 to +131
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function FFmpegMidiOpusAudio._spawn_process refactored with the following changes:

except subprocess.SubprocessError as exc:
raise ClientException(
"Popen failed: {0.__class__.__name__}: {0}".format(exc)
Expand All @@ -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
Comment on lines -166 to +153
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function is_alone refactored with the following changes:



async def disconnect(voice: VoiceClient):
Expand All @@ -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)
Comment on lines -178 to +163
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ensure_voice refactored with the following changes:

raise CommandError(f"{ctx.author} not connected to a voice channel.")
await connect_to(member.voice.channel)

Expand All @@ -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,
)

Comment on lines -192 to +180
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ensure_can_modify refactored with the following changes:

raise CommandError(f"File {cmd} is not modifiable by {ctx.author}")


Expand Down Expand Up @@ -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"
Comment on lines -229 to +221
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function check_file refactored with the following changes:

return audio or video, archive, soundfont, midi, video


Expand All @@ -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:
Comment on lines -250 to +236
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_audio_info refactored with the following changes:

  • Simplify logical expression using De Morgan identities (de-morgan)

return None
data = [s for s in data["streams"] if s["codec_type"] == "audio"]
if not data:
Expand Down