如何重用命令功能discord.py

时间:2020-06-22 09:40:59

标签: python python-3.x discord discord.py

我有一个音乐机器人,可以广播电台,每个广播都是易于使用的命令。问题是现在有100多个站点,并且更新每个站点的代码变得越来越困难。

@bot.command(aliases=["VAR1", "VAR2"])
@commands.check(if_channel_private)
async def VAR(ctx):
    current_time = datetime.now().strftime("%H:%M")
    station = 'VAR3'
    if len(embed_history.fields) <= 4:
        embed_history.add_field(inline=False, name=f"[{current_time}] Played:", value=f'`{station}`')
    elif len(embed_history.fields) > 4:
        embed_history.remove_field(0)
        embed_history.add_field(inline=False, name=f"[{current_time}] Played:", value=f'`{station}`')
    stream = 'URL VAR4'
    resume = stream
    if len(pause_list) != 0 or len(radio_station) != 0:
        pause_list.clear()
        radio_station.clear()
    voice = get(bot.voice_clients, guild=ctx.guild)
    if voice.is_playing():
        voice.stop()
    try:
        voice.play(FFmpegPCMAudio(stream))
        print(f'Playing {station}')
    except:
        print(f"An error occurred while trying to play {station}")
        await ctx.send(error_message)
    radio_station.append(station)
    pause_list.append(resume)
    embed_st.clear_fields()
    embed_st.add_field(inline=False, name=embed_name,
                       value="VAR5")
    await ctx.send(embed=embed_st)

@VAR.error
async def _pr_error(ctx, error):
    if isinstance(error, commands.CheckFailure):
        if ctx.message.author.voice is None:
            return
        await ctx.send(f"Only users in __the same private voice channel__ can change the station!")
    else:
        await ctx.send(f"```css\n"
                       "[ERROR: Unexpected error has occured!]"
                       "```")
        print(error)

这是每个电台的外观。是否可以只编写一次然后为每个站调用它?而且只需要更改变量(VAR)?否则,它将使用重复代码使整个文本文件膨胀。

1 个答案:

答案 0 :(得分:1)

我不检查此代码,但可能是可行的。创建函数,并将变量stationstream发送给它:

@bot.command(aliases=["VAR", "VAR"])
@commands.check(if_channel_private)
async def VAR(ctx):
    await some_function('VAR', 'URL_VAR')


# Your function for all stations
async def some_function(station, stream):
    current_time = datetime.now().strftime("%H:%M")
    if len(embed_history.fields) <= 4:
        embed_history.add_field(inline=False, name=f"[{current_time}] Played:", value=f'`{station}`')
    elif len(embed_history.fields) > 4:
        embed_history.remove_field(0)
        embed_history.add_field(inline=False, name=f"[{current_time}] Played:", value=f'`{station}`')
    resume = stream
    if len(pause_list) != 0 or len(radio_station) != 0:
        pause_list.clear()
        radio_station.clear()
    voice = get(bot.voice_clients, guild=ctx.guild)
    if voice.is_playing():
        voice.stop()
    try:
        voice.play(FFmpegPCMAudio(stream))
        print(f'Playing {station}')
    except:
        print(f"An error occurred while trying to play {station}")
        await ctx.send(error_message)
    radio_station.append(station)
    pause_list.append(resume)
    embed_st.clear_fields()
    embed_st.add_field(inline=False, name=embed_name,
                       value="VAR")
    await ctx.send(embed=embed_st)