python - 我怎样才能减少代码?不和谐机器人 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.
解决方案
首先,避免逻辑重复是很好的。这是一件非常好的事情因为您的目标是编写更好的代码,我假设您发布的代码是为了说明,但如果您的代码实际上是这样的,我建议您避免命名函数(或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')
推荐阅读
- php - Wordpress - 向用户添加多个角色,foreach 只添加第一个角色
- javascript - 更新 vuejs 中的输入值( v-model )
- sapui5 - 智能过滤栏不出现
- android - AGP 7.0.0-alpha15 后如何更改版本代码
- android - 如何从已添加到 android 项目中的颤振模块中移动 android 本机活动
- sharepoint - 如何格式化 Power Automate 的“创建 HTML 表”以在电子邮件中显示指向 SharePoint 的超链接
- bash - sed,在分隔符后的第 N 个位置插入空格
- python - 问题类型错误:参数必须是字符串或数字
- typescript - 处理 TS 源文件动态导入 `typescript` 不会导入 ts 命名空间中的所有类型
- flutter - 将浮点数转换为 dart 中的 modbus 寄存器