我怎样才能减少代码?不和谐机器人蟒蛇

时间:2021-05-01 22:55:58

标签: python discord discord.py bots

一段时间以来,我一直在为我和我的朋友制作不和谐机器人。 我已经制作了条形音箱。看起来像这样

@bot.command(aliases = ['A'])   
async def a(ctx):
    voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
    if voice==None:
      channel = ctx.message.author.voice.channel
      await channel.connect()
    guild = ctx.guild
    voice_client: discord.VoiceClient = discord.utils.get(bot.voice_clients, guild=guild)
    audio_source = discord.FFmpegPCMAudio('mp3//a.mp3')
    if not voice_client.is_playing():
        voice_client.play(audio_source, after=None)
    await ctx.channel.purge(limit = 1)

    #2
@bot.command(aliases = ['q'])   
async def B(ctx):
    voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
    if voice==None:
      channel = ctx.message.author.voice.channel
      await channel.connect()
    guild = ctx.guild
    voice_client: discord.VoiceClient = discord.utils.get(bot.voice_clients, guild=guild)
    audio_source = discord.FFmpegPCMAudio('mp3//b.mp3')
    if not voice_client.is_playing():
        voice_client.play(audio_source, after=None)
    await ctx.channel.purge(limit = 1)

如何以更短的形式获得相同的效果?我的意思是,我不想每次都重复相同的代码部分 -

voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
    if voice==None:
      channel = ctx.message.author.voice.channel
etc.
etc.

1 个答案:

答案 0 :(得分:2)

首先,避免逻辑重复很好。这真是一件值得寻找的好事情 由于您的目标是编写更好的代码,我假设您发布的代码是为了说明,但以防万一您的代码实际上是这样,我建议您避免命名函数(或变量,或任何与此相关的内容)没有明确的名字。 a 是最糟糕的函数名称。

async def play_sound(ctx, filename:str) -> None:
voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)
    if voice==None:
      channel = ctx.message.author.voice.channel
      await channel.connect()
    guild = ctx.guild
    voice_client: discord.VoiceClient = discord.utils.get(bot.voice_clients, guild=guild)
    audio_source = discord.FFmpegPCMAudio(f'mp3//{filename}.mp3')
    if not voice_client.is_playing():
        voice_client.play(audio_source, after=None)
    await ctx.channel.purge(limit = 1)
    
@bot.command(aliases = ['A'])   
async def a(ctx):
    await play_sound(ctx, 'a')
    


@bot.command(aliases = ['q'])   
async def B(ctx):
   await play_sound(ctx, 'b')