如何使 discord.py 转换器通过一个参数并时间 return 一个值

How to make a discord.py converter pass thorugh a argument and time return a value

我想做的是这样的:
有一个命令 modifyImage

@commands.command()
async def modifyImage(ctx: Context, imgName: DefaultImageConverter, size: int):
    img = imageList[imgName]
    img.scale(size)

一个命令setDefaltImage

@commands.command()
async def setdefaultImage(ctx: Context, imgName: str):
    global defaultImg
    defaultImg = imgName

和转换器 DefaultImageConverter

class DefaultImageConverter(commands.Converter):
async def convert(self, ctx, imgName):
    if imgName not in imageList:
        if defaultImg != '':
            return defaultImg
        if defaultImg == '':
            ctx.reply("you didn't pass a image and doesn't have a defalt image")
            raise BadArgument
    elif imgName in imageList:
        return imgName

DefaultImageConverter 将是一个转换器,检查图像是否存在,return 如果不存在,return 默认图像如果存在,即使不存在,他也会报错

但是程序不能这样工作,因为如果我使用命令!modifyImage 100,数字'100'将不会传递给参数size,因为从技术上讲转换有效

所以我需要做

@commands.command()
async def modifyImage(ctx: Context, imgName: typing.Optional[DefaultImageConverter], size: int):
    if imgName == None:
        if defaultImg != '':
            imgName =  defaultImg
        else:
            ctx.send("you didn't pass a image and doesn't have a defalt image")
            return
            
    img = imageList[imgName]
    img.scale(size)

转换器是

class DefaultImageConverter(commands.Converter):
    async def convert(self, ctx, imgName):
        if imgName not in imageList:
            return BadArgument
        else:
            return imgName

我需要做些什么来使用第一个选项,因为 if imgName == None: 部分变得非常重复,并且每个修改图像的函数都有这个


tl;博士

我想做一个discord.py转换器,同时return一个值,把当前参数值传递给下一个参数

我知道转换器 'pass the argument' 的唯一方法是使用 typing.Optional 并在转换器中引发错误,但这样做会使参数变为 None

but the program doesn't work this way, because if i use the command !modifyImage 100 the number '100' won't be passed to the parameter size, because technically the conversion worked

就像常规函数一样,您不能将可选参数放在强制参数之前。您需要重新排序您的论点,以便您的 size 首先是预期的, 然后是 您的 imgName.

what i need to do for use something like the first option, because the if imgName == None: part become very repetetive, and every function that modify a image has this

你的第一个选项基本上没问题,你只需要按照提到的那样交换参数,并在你的转换器中包含 None 检查。试试这个:

class DefaultImageConverter(commands.Converter):
    async def convert(self, ctx, imgName):
        if imgName is None or imgName not in imageList:
            if defaultImg:
                return defaultImg
            else:
                ctx.reply("you didn't pass a image and doesn't have a defalt image")
                raise BadArgument
        else:
            return imgName

@commands.command()
async def modifyImage(ctx: Context, size: int,
                      imgName: typing.Optional[DefaultImageConverter]):
    img = imageList[imgName]
    img.scale(size)

那么您的 !modifyImage 100 示例以及 !modifyImage 100 someImage.

应该可以工作