首页 > 解决方案 > 我怎样才能减少代码?不和谐机器人 python

问题描述

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

@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.

标签: pythondiscorddiscord.pybots

解决方案


首先,避免逻辑重复是很好的。这是一件非常好的事情因为您的目标是编写更好的代码,我假设您发布的代码是为了说明,但如果您的代码实际上是这样的,我建议您避免命名函数(或vars 或其他任何东西)没有明确的名称。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')

推荐阅读